2

I have a sequence of string which has a python list within it. It looks like this

"['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']"

How can I can retrieve the string enclosed by [] as the list data type of python?

a_parida
  • 516
  • 6
  • 23
  • 4
    Possible duplicate of [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – Aquarthur Nov 20 '18 at 11:47
  • 3
    Possible duplicate of [How to conver String to List withou using eval(Python)](https://stackoverflow.com/questions/19418566/how-to-conver-string-to-list-withou-using-evalpython) – Netwave Nov 20 '18 at 11:47
  • Is it sure that the string only contains the list or may it contain something else too? I.e., is the following possible: `"This is my list ['a', 'b', 'c']. It's a beautiful list.`? – Tobias Brösamle Nov 20 '18 at 11:48

4 Answers4

2

Use a regular expression to extract the list:

re.findall("\'(.*?)\'",st)

#['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']
yatu
  • 75,195
  • 11
  • 47
  • 89
2

Use the literal_eval function from the standard library:

>>> from ast import literal_eval
>>> literal_eval("['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']")
['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']

This is way more safe than using eval directly (source).

julienc
  • 15,239
  • 15
  • 74
  • 77
1

Use python's eval function to evaluate the string and get a list

>>> x = "['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']"
>>> eval(x)
['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']
>>> type(eval(x))
<class 'list'>

NOTE:

eval is dangerous in case you are exposing the code to open world such as a website or an api. eval executes in global namespace and hence could be dangerous.

Example: eval(os.listdir()) gives all files and folder in working directory.

Vishnudev
  • 7,765
  • 1
  • 11
  • 43
0

You can also achieve your desired result using string operations and slicing:

string = "['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']"
wordList = list(map(lambda elem: elem.replace('\'','') ,string[1:-1].split(', ')))
print(wordList)

Output:

['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']
Vasilis G.
  • 6,470
  • 3
  • 15
  • 27