0

I have a function in python

def func(x):
   #  x is int
   for cell in list1:
      # gets each cell
      print cell

how to use eval to calculate new string?

Any ideas please?

Thanks

Ragnarok
  • 170
  • 14
  • You start by recognizing that a list of strings is a terrible way to encode a list of functions. `list1` should be `[lambda x: x+3, lambda x: x/3, lambda x: x*3]`. – chepner Jan 28 '16 at 19:29
  • 1
    Possible duplicate of [Evaluating a mathematical expression in a string](http://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string) – timgeb Jan 28 '16 at 19:35

1 Answers1

1

You don't want to substitute. You want to evaluate the expression. I would suggest you try something like this:

variables = { x: 900 }
cell = 'x+3'
result = eval(cell, locals=variables)

This will evaluate the cell expression using python syntax. As long as your cell formulas are simple enough, that will probably be okay. If you start trying to do Excel spreadsheet formulas, you will need to do a lot more work.

aghast
  • 14,785
  • 3
  • 24
  • 56
  • Thank you for the response.. but where should I write the variables ={} and cell = {} ? – Ragnarok Jan 28 '16 at 19:42
  • That depends on you. The cell='' stuff can be replaced by `for cell in cells:` or whatever code you need to run to evaluate all the cells. The `variables={}` can either be an outer thing (like, this applies to all cells) or a specific thing for each cell. It will be based on the requirements of your app. – aghast Jan 28 '16 at 22:53