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
  • 963,270
  • 265
  • 3,804
  • 3,187
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
  • 963,270
  • 265
  • 3,804
  • 3,187
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
  • 45,811
  • 27
  • 120
  • 136
Michael T
  • 993
  • 8
  • 12
  • 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