Let's say I have this string like this:
string = ("['1.345', '1.346', '1.347']")
So it's formatted like a list, but I need to convert it to an actual list object. How can I do that?
-
1Where did the list come from?Winston Ewert– Winston Ewert2012年02月27日 00:06:08 +00:00Commented Feb 27, 2012 at 0:06
4 Answers 4
You can use literal_eval from the ast module.
>>> string = ("['1.345', '1.346', '1.347']")
>>> import ast
>>> lst = ast.literal_eval(string)
>>> lst
['1.345', '1.346', '1.347']
BTW, you don't need the parentheses around the string. string = "['1.345', '1.346', '1.347']" works just fine.
1 Comment
eval because it only evaluates literals, not actual code. So there isn't a security issue with taking arbitrary user input.string = ("['1.345', '1.346', '1.347']")
lst = eval(string)
2 Comments
literal_eval is betterIt might help if we knew where these strings come from. In general, Praveen's answer is a good one regarding the example you give. I'd like to mention, though, that using doublequotes instead of singlequotes in your string would make the whole thing valid JSON, in which case you could also do:
import json
json.loads('["1.345", "1.346", "1.347"]') # [u'1.345', u'1.346', u'1.347']
Measuring the performance:
import timeit
s = """\
import ast
ast.literal_eval("['1.345', '1.346', '1.347']")
"""
t = timeit.Timer(stmt=s)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000) / 100000)
Result: 21.25 usec/pass
vs.
import timeit
s = """\
import json
json.loads('["1.345", "1.346", "1.347"]')
"""
t = timeit.Timer(stmt=s)
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000) / 100000)
Result: 6.32 usec/pass
Maybe this is an alternative for you.
2 Comments
I would strip '[',']'.etc and use split() method on that string..
lst = string.replace('[','').replace(']','').replace("'",'').replace(" ",'').split(',')
I think it's safer than eval if the string is well formatted, but not quite efficient though, because Python has to build a new string with every replace method.