list_val = '["apple", "blue", "green", "orange", "cherry", "white", "red", "violet"]'
print type(list_var)
str
print type(list_var[0])
'['
I read list_val values from a file and how to convert list_var to list ? so that list_var [0] should be 'apple'.
asked Oct 12, 2015 at 5:26
Sreejithc321
3174 silver badges19 bronze badges
-
1Why not configure list_val as list and for each value, just append the item to the list?Avihoo Mamka– Avihoo Mamka2015年10月12日 05:29:23 +00:00Commented Oct 12, 2015 at 5:29
-
How did the file end up like that in the first place? Are you trying to remember some list contents between runs of the program?Karl Knechtel– Karl Knechtel2015年10月12日 05:35:56 +00:00Commented Oct 12, 2015 at 5:35
4 Answers 4
>>> list_val = '["apple", "blue", "green", "orange", "cherry", "white", "red", "violet"]'
>>>
>>> from ast import literal_eval
>>> list_val = literal_eval(list_val)
>>> list_val[0]
'apple'
answered Oct 12, 2015 at 5:28
John La Rooy
306k54 gold badges378 silver badges514 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I recommend you use json.
import json
list_val = '["apple", "blue", "green", "orange", "cherry", "white", "red", "violet"]'
a = json.loads(list_val)
print a
# [u'apple', u'blue', u'green', u'orange', u'cherry', u'white', u'red', u'violet']
print type(a)
# <type 'list'>
print a[0]
# 'apple'
answered Oct 12, 2015 at 5:31
Burger King
2,9753 gold badges23 silver badges47 bronze badges
1 Comment
John La Rooy
This certainly works for the example input. The best choice depends on matching the source encoding to the decoder. The origin may very well be JSON in this case.
Another way is using regex:
>>> import re
>>> list_val = '["apple", "blue", "green", "orange", "cherry", "white", "red", "violet"]'
>>> result = re.findall(r'\"([^\"]+)\"', list_val)
>>> result[0]
'apple'
answered Oct 12, 2015 at 12:32
Mayur Koshti
1,89218 silver badges21 bronze badges
Comments
lang-py