Reputation: 1591
I have a tuple of characters like such:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
How do I convert it to a string so that it is like:
'abcdgxre'
Upvotes: 156
Views: 460064
Reputation: 1
If just using str()
for a tuple as shown below:
t = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
print(t, type(t))
s = str(t) # Here
print(s, type(s))
Only the type can be changed from tuple
to str
without changing the value as shown below:
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'tuple'>
('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e') <class 'str'>
Upvotes: 0
Reputation: 903
This works:
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
It will produce:
'abcdgxre'
You can also use a delimiter like a comma to produce:
'a,b,c,d,g,x,r,e'
By using:
','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Upvotes: 21
Reputation: 7806
here is an easy way to use join.
''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Upvotes: 33
Reputation:
Use str.join
:
>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
Upvotes: 237