4

I have a list as a string like this:

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

I want to retrieve the list from the string, like this:

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

How can I do that? Itertools or list function have not given me the proper result. Thanks

  • actually `"["USA", "Canada", "Mexico", "Brazil"]"` is not a python string. I think you're trying to say that your string is `'["USA", "Canada", "Mexico", "Brazil"]'` with double `'`. – Chiheb Nexus Jul 26 '17 at 06:11
  • 1
    @ChihebNexus My bad. It's fixed now. –  Jul 26 '17 at 06:14
  • @ChihebNexus I know what is your mean. BUT, if there has a file `data.log`, which content is `"["USA", "Canada", "Mexico", "Brazil"]"`. How to deal with it? – CHENJIAN Jul 26 '17 at 06:29
  • 1
    @CHENJIAN In that case you need to parse your data and replace the external `"` by `'` otherwise you'll have a not valid python strings. One way to do it is using `regex`. – Chiheb Nexus Jul 26 '17 at 06:31
  • 1
    @ChihebNexus One more step than this question. I get it and thanks. – CHENJIAN Jul 26 '17 at 06:35

2 Answers2

4

you can evaluate the string to a list using eval:

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

Executing this on python shell, gives a list:

>>> eval('["USA", "Canada", "Mexico", "Brazil"]')
['USA', 'Canada', 'Mexico', 'Brazil']
>>> 
Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
2

You can use literal_eval from ast module like this example:

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

Output:

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

Also, don't use eval(), use literal_eval() instead. See this answer for more details.

Chiheb Nexus
  • 9,104
  • 4
  • 30
  • 43