pythonina
pythonina

Reputation: 21

Convert array to string

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?

Upvotes: 2

Views: 2181

Answers (3)

Kamil Szot
Kamil Szot

Reputation: 17817

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.

Upvotes: 3

rocksportrocker
rocksportrocker

Reputation: 7429

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.

Upvotes: 1

Gary Kerr
Gary Kerr

Reputation: 14450

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]

Upvotes: 0

Related Questions