2

I have a reeeealy huge string, which looks like ['elem1','elem2',(...)] and contains about 100,000(!) elements. What is the best method to change it back to a list?

3
  • Um, is it convert to string or convert to array you are looking for? Commented Jun 30, 2010 at 8:30
  • Are you sure it is a string and you are not doing something like repr(yourlist)? Care to share some code? Commented Jun 30, 2010 at 8:36
  • yes, it is string from text file, which was writed by me - eval works well Commented Jun 30, 2010 at 8:52

3 Answers 3

3

eval("['elem1','elem2']") gives you back list ['elem1','elem2']

If you had string looking like this ["elem1","elem2",(...)] you might use json.read() (in python 2.5 or earlier) or json.loads() (in python 2.6) from json module to load it safely.

Sign up to request clarification or add additional context in comments.

2 Comments

Does the JSON parser distinguish between single- and double-quotes?
It seems so. Trying to json.read("['a']") gives json.ReadException: Input is not valid JSON: '['a']'
1

One possible solution is:

input = "['elem1', 'elem2' ] "
result_as_list = [ e.strip()[1:-1] for e in input.strip()[1:-1].split(",") ]

This builds the complete result list in memory. You may switch to generator expression

result_as_iterator =  ( e.strip()[1:-1] for e in input.strip()[1:-1].split(",") )

if memory consumption is a concern.

Comments

0

If you don't want to use eval, this may work:

big_string = """['oeu','oeu','nth','nthoueoeu']"""

print big_string[1:-2].split("'")[1::2]

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.