1

I have a string like

"['foo', 'bar', 'baz', 0, 1]"

and want to convert this into a list like

['foo', 'bar', 'baz', 0, 1]

I have tried various methods of slicing the string into a list, but while that does work, it is keeping 0 and 1 as strings, while also being unable to change easily for different lists.

Is there an easier way, aside from massive for loops and slicing?

Prune
  • 76,765
  • 14
  • 60
  • 81
  • I would ask "Why the downvote?" but I've realised by now that whenever I ask a question in SO that I'm guaranteed to lose some rep, so I won't bother. (Yes I appreciate the irony of bothering to write this.) – caird coinheringaahing Aug 03 '17 at 22:42
  • downvote probably because this is a duplicate... – jmoon Aug 03 '17 at 22:46
  • @jmoon that's no reason to downvote. It's not my fault that someone else in the millions, yes millions, of SO users had the same problem, and a downvote should be used to suggest that the post can be improved, not that it's been done before. – caird coinheringaahing Aug 03 '17 at 22:55
  • People abuse the downvote button. I'm not saying I downvoted (I see no reason to), but people do mistake the downvote button for flagging. Also suggesting that if you want to continue this discussion that this be moved to the meta. – jmoon Aug 03 '17 at 22:58
  • 1
    @jmoon no need to move this to Meta; I'm well aware that people don't know how to vote on SE. Just a shame really. – caird coinheringaahing Aug 03 '17 at 22:59

3 Answers3

2

Not that I'm advocating for the use of eval, you can just do

eval("['foo', 'bar', 'baz', 0, 1]")

I'll suggest that you instead use ast.literal_eval, a "safer" eval.

cs95
  • 379,657
  • 97
  • 704
  • 746
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62
  • You have my vote..when security is not an issue eval is a useful too...since you might not want to import an entire module. I also believe that this was the purpose eval built in module was made for.. is it not? – repzero Aug 03 '17 at 22:42
2

If it just contains primitive objects (like strings, integers and such like) you can use ast.literal_eval:

>>> import ast
>>> ast.literal_eval("['foo', 'bar', 'baz', 0, 1]")
['foo', 'bar', 'baz', 0, 1]
MSeifert
  • 145,886
  • 38
  • 333
  • 352
2

Consider the literal_eval function for a direct conversion. If you care to do your own processing, then try this:

in_str = "['foo', 'bar', 'baz', 0, 1]"
no_bracket = in_str[1:-1]
print no_bracket
my_list = no_bracket.split(', ')
print my_list

Output:

["'foo'", "'bar'", "'baz'", '0', '1']

Can you finish from there? Each element is a string image of the value you want. For the true strings, you'll have to strip off the extra quotation marks; for the numeric values, you'll have to use int().

To tell which is which, try the isdigit method.

cs95
  • 379,657
  • 97
  • 704
  • 746
Prune
  • 76,765
  • 14
  • 60
  • 81