112
votes

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'
4
Try this also reduce(add, ('a', 'b', 'c', 'd')) - Grijesh Chauhan
what is add in this exmple @GrijeshChauhan? - Steve
@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 - Grijesh Chauhan

4 Answers

187
votes

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.

>>>
30
votes

here is an easy way to use join.

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

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

Easiest way would be to use join like this:

>>> myTuple = ['h','e','l','l','o']
>>> ''.join(myTuple)
'hello'

This works because your delimiter is essentially nothing, not even a blank space: ''.