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?

3

4 Answers 4

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).

Sign up to request clarification or add additional context in comments.

Comments

2

Use a regular expression to extract the list:

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

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

Comments

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.

2 Comments

dont use eval, use ast.literal_eval instead
That answer is dangerous.
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?']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.