Alex
Alex

Reputation: 2074

How to replace variables in equation in python

I have string with some equation, that include variables. For example:

eq='(a+1)*c-d'

Also I have dictionary with values for variables. For example:

val={'a':5,'c':'k','d':'300n'}

As You can see in same cases value of variable can be other variable, and in some cases not all variables from eq will be in val.

I need to replace all variables in eq with values from val. Of cause straight forward code will be something like:

for v in val.keys():
  eq=re.sub(v,val[v],eq)

But this code will fail in some cases. For example when in variables list will be variables "n" and "nn"

So, can someone think about better solution? Thank you.

Upvotes: 1

Views: 4484

Answers (2)

whardier
whardier

Reputation: 705

Another approach requires changing the formula around just a smidge and uses the string function 'format'.

Using keyword arguments (not very programmatic):

>>> '({a}+1)*{c}-{d}'.format(a=5, c='k', d='300n')
'(5+1)*k-300n'

Or alternatively using a dict:

>>> '({a}+1)*{c}-{d}'.format(**{'a': 5, 'c': 'k', 'd': '300n'})
'(5+1)*k-300n'

Doing so may help users identify when something isn't replaced, or is meant to be replaced, and simplifies the code quite a bit.

Upvotes: 0

Oren
Oren

Reputation: 2807

Try:

for k,v in val.items():
    eq = re.sub(r'\b' + k + r'\b', v, eq)

This will search for variables by their full name, i.e. if the val = {'x': '5'} and the equation contains substrings like "xx", "x2", or even "2x", these strings will not be replaced.

Upvotes: 1

Related Questions