Python convert tuple to string

PythonStringTuples

Python Problem Overview


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'

Python Solutions


Solution 1 - Python

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.

>>>

Solution 2 - Python

here is an easy way to use join.

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

Solution 3 - Python

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

Solution 4 - Python

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: ''.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionintel3View Question on Stackoverflow
Solution 1 - Pythonuser2555451View Answer on Stackoverflow
Solution 2 - PythonBack2BasicsView Answer on Stackoverflow
Solution 3 - Pythonuser3248578View Answer on Stackoverflow
Solution 4 - PythonW_water_mView Answer on Stackoverflow