0

i have turned a list of words into a string now i want to turn them back into a list but i dont know how, please help

temp = ['hello', 'how', 'is', 'your', 'day']
temp_string = str(temp)

temp_string will then be "[hello, how, is, your, day]"

i want to turn this back into a list now but when i do list(temp_string), this will happen

['[', "'", 'h', 'e', 'l', 'l', 'o', "'", ',', ' ', "'", 'h', 'o', 'w', "'", ',', ' ', "'", 'i', 's', "'", ',', ' ', "'", 'y', 'o', 'u', 'r', "'", ',', ' ', "'", 'd', 'a', 'y', "'", ']']

Please help

  • Depending on your needs, consider splitting on spaces, or using regex to split on whitespace or word boundaries. – CollinD Jan 20 '17 at 00:31
  • Why would you want to do this? – juanpa.arrivillaga Jan 20 '17 at 00:34
  • `eval(temp_string)` # prints -> `['hello', 'how', 'is', 'your', 'day']` – chickity china chinese chicken Jan 20 '17 at 00:35
  • So do you want ['hello', 'how', 'is', 'your', 'day'] as final output or ['[', "'", 'h', 'e', 'l', 'l', 'o', "'", ',', ' ', "'", 'h', 'o', 'w', "'", ',', ' ', "'", 'i', 's', "'", ',', ' ', "'", 'y', 'o', 'u', 'r', "'", ',', ' ', "'", 'd', 'a', 'y', "'", ']']? – Vaishali Jan 20 '17 at 00:39
  • Actually, it would be more accurate to say that `temp_string will then be "['hello', 'how', 'is', 'your', 'day']"`, *with* the single quotes around each word. – paxdiablo Jan 20 '17 at 00:42

3 Answers3

1

You can do this easily by evaluating the string. That's not something I'd normally suggest but, assuming you control the input, it's quite safe:

>>> temp = ['hello', 'how', 'is', 'your', 'day'] ; type(temp) ; temp
<class 'list'>
['hello', 'how', 'is', 'your', 'day']

>>> tempstr = str(temp) ; type(tempstr) ; tempstr
<class 'str'>
"['hello', 'how', 'is', 'your', 'day']"

>>> temp2 = eval(tempstr) ; type(temp2) ; temp2
<class 'list'>
['hello', 'how', 'is', 'your', 'day']
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

Duplicate question? Converting a String to a List of Words?

Working code below (Python 3)

import re
sentence_list = ['hello', 'how', 'are', 'you']
sentence = ""
for word in sentence_list:
    sentence += word + " "
print(sentence)
#output: "hello how are you "

word_list = re.sub("[^\w]", " ", sentence).split()
print(word_list)
#output: ['hello', 'how', 'are', 'you']
Community
  • 1
  • 1
Jcloud
  • 41
  • 3
-1

You can split on commas and join them back together:

temp = ['hello', 'how', 'is', 'your', 'day']
temp_string = str(temp)

temp_new = ''.join(temp_string.split(','))

The join() function takes a list, which is created from the split() function while using ',' as the delimiter. join() will then construct a string from the list.

the_constant
  • 681
  • 4
  • 11