简体   繁体   中英

Convert strings to list Python

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'.

>>> 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'

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'

you can use eval function. Be careful what you pass to eval though, malicious things can happen!

list_var = eval(list_val)

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM