Question

I have extracted data from a csv file using python. The data within the csv file looks in the following format:

a=(10100*b)+(-1289201*c)+(12312312*d)

I wrote the code to extract it from the csv file.

ar=[]
ins = open(log,"r")
for line in ins:
        ar.append(line)
ins.close()

so, ar[0]='a=(10100*b)+(-1289201*c)+(12312312*d)'

Now, I need to subsitute the values of b, c and d with a specific floating point variables.

So,I did the following:

map = [ ('b','10'), ('c', '20'), ('d','100') ]
for k, v in map: 
 ar[0] = ar[0].replace(k,v)

The problem now is I am unable to do any arithmetic operations on the final result, that is, the output is in the following format.

`ar[0]='a=(10100*10)+(-1289201*20)+(12312312*100)'`

Is there a way in which I can perform some arithmetic operation on the following list format. I tried to strip the list, but that did not help.

Was it helpful?

Solution

>>> s = 'a=(10100*10)+(-1289201*20)+(12312312*100)'
>>> index = s.find('=') + 1
>>> eval(s[index:])

OTHER TIPS

the answer above is pretty good. here is another way with 1 line less:

>>> s = 'a=(10100*10)+(-1289201*20)+(12312312*100)'
>>> exec s

you can check the output:

>>> a
1205548180

the exec statement is used to execute expressions, not only evaluate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top