Parsing excel string to python

258 Views Asked by At

I would like to store a string value in excel, e.g. ['1','2'], and parse it in python to use as a calculation array. Python accepts this value as string but when I tried to convert the value to int or float, I run into an value error message saying that python can't convert to string to float

Input from Excel ['1','2','3'] Desired output in python ['1','2','3']

Problem: When I parse the input, python recognizes as a string "['1','2']" and I can not convert it to the desired output:

example for code:

s = "['1','2','3']"
for i in range(1,3)
    print 1 + float(s[i]) 
1

There are 1 best solutions below

2
Mike Bell On

I think this does what you're looking for:

s="['1','2','3']"
nums = [float(num[1:-1]) for num in s[1:-1].split(',')]

[1.0, 2.0, 3.0]

Note that this assumes A LOT about the cleanliness of your input

This also works, although eval is usually avoided unless you absolutely trust your data source.

nums = [float(num) for num in eval(s)]