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?
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?
Use a regular expression to extract the list:
re.findall("\'(.*?)\'",st)
#['How', 'Quebec', 'nationalists', 'see', 'province', 'nation', '1960s?']
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).
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.
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?']