153

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'
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
intel3
  • 1,561
  • 2
  • 9
  • 4
  • 2
    Try this also `reduce(add, ('a', 'b', 'c', 'd'))` – Grijesh Chauhan Oct 28 '13 at 17:57
  • what is `add` in this exmple @GrijeshChauhan? – Steve Sep 03 '14 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](http://codepad.org/010AxubW) – Grijesh Chauhan Sep 04 '14 at 06: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']]},)``` – Pravin Feb 08 '23 at 11:16
  • @Pravin Those aren't tuples. – Tommaso Thea Mar 14 '23 at 21:10

5 Answers5

230

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.

>>>
33

here is an easy way to use join.

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))
Back2Basics
  • 7,406
  • 2
  • 32
  • 45
  • This was the most useful answer for me (+1), but what an inelegant way to do this. In MATLAB it's just [`num2str`](https://www.mathworks.com/help/matlab/ref/mat2str.html). – Nike Jan 20 '23 at 15:58
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'))
user3248578
  • 905
  • 8
  • 18
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'>
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
-1

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

W_water_m
  • 49
  • 1