How to remove quotation marks and get list in python?

I have a list as a string:

"['USA', 'Canada', 'Mexico', 'Brazil']"

I want to get a list from a string, for example:

['USA', 'Canada', 'Mexico', 'Brazil']

How can i do this? Itertools or a list function did not give me the correct result. Thanks

+4
source share
2 answers

you can evaluate the row in the list using eval:

 eval('["USA", "Canada", "Mexico", "Brazil"]')

Doing this in a python shell gives a list:

>>> eval('["USA", "Canada", "Mexico", "Brazil"]')
['USA', 'Canada', 'Mexico', 'Brazil']
>>> 
+5
source

You can use literal_evalfrom the module ast, as in this example:

from ast import literal_eval as le
data = le('["USA", "Canada", "Mexico", "Brazil"]')
print(data)

Conclusion:

['USA', 'Canada', 'Mexico', 'Brazil']

Also, do not use eval(), use literal_eval(). See more details.

+3
source

Source: https://habr.com/ru/post/1682289/


All Articles