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

2
  • 1
    Why not configure list_val as list and for each value, just append the item to the list? Commented 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? Commented Oct 12, 2015 at 5:35

4 Answers 4

6
>>> 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'
Sign up to request clarification or add additional context in comments.

Comments

4

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'

1 Comment

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

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

list_var = eval(list_val)

1 Comment

eval is evil please use literal_eval instead
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.