0

I know in python there is a way to turn a word or string into a list using list(), but is there a way of turning it back, I have:

phrase_list = list(phrase)

I have tried to change it back into a string using repr() but it keeps the syntax and only changes the data type.

I am wondering if there is a way to turn a list, e.g. ['H','e','l','l','o'] into: 'Hello'.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Trogz64
  • 13
  • 1

2 Answers2

5

Use the str.join() method; call it on a joining string and pass in your list:

''.join(phrase)

Here I used the empty string to join the elements of phrase, effectively concatenating all the characters back together into one string.

Demo:

>>> phrase = ['H','e','l','l','o']
>>> ''.join(phrase)
'Hello'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Using ''.join() is the best approach but you could also you a for loop. (Martijn beat me to it!)

hello = ['H','e','l','l','o']

hello2 = ''
for character in hello:
    hello2 += character
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Michael T
  • 1,033
  • 9
  • 13
  • Please, his name is *Martijn* and not Martijin :( – Bhargav Rao Mar 22 '15 at 11:19
  • You _could_ do this, but it's very inefficient if the list is long, since it has to allocate memory for a new copy of the `hello2` string (and copy its current contents) each time around the loop. – PM 2Ring Mar 22 '15 at 11:25