Python convert tuple to string
Asked Answered
B

4

154

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'
Bertrambertrand answered 28/10, 2013 at 17:45 Comment(5)
Try this also reduce(add, ('a', 'b', 'c', 'd'))Moonier
what is add in this exmple @GrijeshChauhan?Skilful
@Skilful You need to import add function from operator module. Btw "".join better suits here but if you want to add different types of objects you can use add Check this working exampleMoonier
@intel3, How can we remove the tuple outside of the dictionary??({'entities': [[44, 58, 'VESSEL'], [123, 139, 'VESSEL'], [146, 163, 'COMP'], [285, 292, 'ADDR'], [438, 449, 'ADDR'], [452, 459, 'ADDR']]},)Wax
@Wax Those aren't tuples.Beehive
W
231

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.

>>>
Wachter answered 28/10, 2013 at 17:46 Comment(3)
Doesn't work if tuple contains numbers. Try tup = (3, None, None, None, None, 1406836313736)Tritium
For numbers you can try this: ''.join(map(str, tup))Hierocracy
For Numbers and None please try ''.join(map(lambda x: str(x or ''), (None, 1, 2, 'apple')))Tamar
B
33

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Bisectrix answered 28/10, 2013 at 17:52 Comment(0)
C
21

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'))
Contributory answered 29/11, 2018 at 3:49 Comment(1)
Of course it works. It was marked as the accepted answer 5 years before you posted.Disclamation
M
0

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'>
Mesdemoiselles answered 14/12, 2022 at 17:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.