157

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'
5
  • 2
    Try this also reduce(add, ('a', 'b', 'c', 'd')) Commented Oct 28, 2013 at 17:57
  • what is add in this exmple @GrijeshChauhan? Commented Sep 3, 2014 at 16:58
  • @Steve 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 example Commented Sep 4, 2014 at 6:39
  • @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']]},) Commented Feb 8, 2023 at 11:16
  • @Pravin Those aren't tuples. Commented Mar 14, 2023 at 21:10

4 Answers 4

239

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.

>>>
Sign up to request clarification or add additional context in comments.

3 Comments

Doesn't work if tuple contains numbers. Try tup = (3, None, None, None, None, 1406836313736)
For numbers you can try this: ''.join(map(str, tup))
For Numbers and None please try ''.join(map(lambda x: str(x or ''), (None, 1, 2, 'apple')))
33

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

Comments

22

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'))

1 Comment

Of course it works. It was marked as the accepted answer 5 years before you posted.
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'>

1 Comment

This comment does not convert to 'abcdgxre' as asked...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.