This question already has answers here:
Safety of Python 'eval' For List Deserialization
(5 answers)
Closed 8 years ago.
In my python code, a user enters a mathematical expression. I want to replace the variables with integer values and calculate the result. I can user regular expression in python to replace the variables with integer values but I cant calculate the sum as the replaced string I get is of type string. I can do it in tcl. It has a built in expr command where I simply pass the string and it automatically converts it to mathematical expression and calculates the result. Is there a way to do the same in python?
Thank you
Yes there is eval.
for example:
a=3
b=4
s="(a*a+b*b)**.5"
eval(s)
But be warned it maybe an security risk.
You may better use SymPy
http://sympy.org/en/index.html
Related
This question already has answers here:
Convert regular Python string to raw string
(12 answers)
Closed 1 year ago.
I wrote a function in Python that takes a file path as an argument. Ideally, I would like to 'concatenate' an r at the beginning to escape the characters, and turn it into r"C:\User\name\location".
I am having trouble finding any solutions- are there any modules to help with this?
You do not require any modifications to the function at all.
def f(path):
...
...
f(r"C:\User\name\location")
The "r" you referred to would be used to form the string that you pass to the function. A string is a string, it does not matter how you form it, but Python offers you different ways of doing so e.g.:
f("C:\\User\\name\\location")
By the time the function is passed the string, the string has already been formed. It now makes no difference how it was formed, only that it has all of the correct characters in all the correct places!
This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 2 years ago.
You may haven't understood the question correctly. So here is it in detailed way:
There is a string, let's say, x='200+350'
so now if I do int(x), it'll give me an error.
I want it to evaluate to 550 which is integer.
How may I do that?
try to use eval method
eval("200+350")
You can use eval()
x = '(2+3)*2'
print( eval(x) )
prints out 10
This question already has an answer here:
Python3: What is the difference between keywords and builtins?
(1 answer)
Closed 3 years ago.
divmod seems to be a builtin as divmod(5,1) gives the correct tuple output with no prior imports (at least in Python 3.7.4).
On the other hand
import keyword
keyword.kwlist
does not list divmod. Also keyword.iskeyword('divmod') returns False. Actually even keyword.iskeyword('int') and keyword.iskeyword('hex') return false. Why is this? What is a keyword and where can we find the complete list of reserved string?
divmod is not a keyword, neither is int or hex. These are objects. You can tell by the fact that they are used with parenthesis to call (). Things like in and for and import are keywords.
This question already has answers here:
Convert fraction to float?
(9 answers)
Closed 8 years ago.
How to change a '14/15' string to a float?
I am trying to extract data from a text file would like to convert '1/3' to a float. float('1/3') doesn't work. I was thinking about splitting into two parts at '/' by 1 and 3 then dividing, but it seems cludgy. Is there a more pythonic way to do this? I'm using Python 2.7
If you only ever need to evaluate simple X/Y fractions:
s = "14/15"
num, denom = map(float, s.split("/", 1))
print(num / denom)
If you need a more complete expression evaluator, take a look at the asteval module.
Using eval() might also see like a nice easy way to do it, but I'd advise against it for security reasons.
If you trust your input:
from __future__ import division
eval('14/15')
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
parsing math expression in python and solving to find an answer
How can I "undo" a string with plus and addition signs in order to calculate them?
I have a string for example:
'6*1+7*1+1*7'
I tried int() but I've got error. How can I undo this whole string to just get a pure integer calculation?
You have to actually implement the operations you want to support by parsing the string and calculating the result. A trivial parser would look like:
>>> import functools,operator
>>> sum(functools.reduce(operator.mul, map(int, summand.split('*')), 1)
... for summand in '6*1+7*1+1*7'.split('+'))
20
Note that the built-in eval may work in a one-off script or an interactive console, but it interprets the string as Python source and therefore allows anyone who controls the string (i.e. the user) to execute arbitrary Python commands.
use eval():
In [177]: eval('6*1+7*1+1*7')
Out[177]: 20
or exec:
In [188]: exec compile('6*1+7*1+1*7','None','single')
Out[188]: 20