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.
Try:
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.