Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String back to List

Tags:

python

string

csv

I messed up yesterday and saved a datframe to csv and in that dataframe I had a column which was a list of strings. Now that list of strings, is a string(of a list of strings) when I import it back into python from a csv. Is there a way I can, upon importing, change it back to a list of strings?

Example:

testList = localGov["DataElements"][4]

testList
Out[62]: "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']"

The closest I have been able to come is using the following but it leaves a whitespace in front of some of the characters.

testList.strip("[]").replace("'","").split(",")
Out[74]: ['Ethnicity', ' Sex', ' Cause of Death', ' Count', ' Percent']
like image 237
Josh Avatar asked Jun 04 '26 17:06

Josh


1 Answers

That's what ast.literal_eval is for :

>>> from ast import literal_eval
>>> 
>>> literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")
['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']
like image 169
Mazdak Avatar answered Jun 06 '26 08:06

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!