0

I'm looking for an easy way to convert a String s, e.g. s = "x+1.0", into a term I can use as a mathematical term. The goal is to find the y-values for some x-values in a specific space.

So for s = "x+1.0" I would get 6 for x=5

TheWaveLad
  • 966
  • 2
  • 14
  • 39

3 Answers3

2

It sounds like you are just trying to convert a string into a Python expression and evaluate it.

You can do this with eval, with all the usual warnings.

x = 5
s = eval("x+1.0") # Now s = 6.
Community
  • 1
  • 1
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1

You can use eval to do so:

>>> x = 5
>>> s = "x+1.0"
>>> eval(s)
6.0
julienc
  • 19,087
  • 17
  • 82
  • 82
0

You should use the eval keyword: it allows the string to be evaluated as an expression.

x = 2
s = "x+1.0"
k = eval(s)
print k

Output: 3.0

Nobi
  • 1,113
  • 4
  • 23
  • 41