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
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:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 1 year ago.
Is it possible to run a String text?
Example:
str = "print(2+4)"
Something(str)
Output:
6
Basically turning a string into code, and then running it.
Use exec as it can dynamically execute code of python programs.
strr = "print(2+4)"
exec(strr)
>> 6
I will not recommend you to use exec because:
When you give your users the liberty to execute any piece of code with the Python exec() function, you give them a way to bend the rules.
What if you have access to the os module in your session and they borrow a command from that to run? Say you have imported os in your code.
Sure is, looks like your "Something" should be exec.
str = "print(2+4)"
exec(str)
Check out this previous question for more info:
How do I execute a string containing Python code in Python?
This question already has answers here:
How to write string literals in Python without having to escape them?
(6 answers)
Closed 5 years ago.
In F# there is something called a literal string (not string literal), basically if a string literal is preceded by # then it is interpreted as-is, without any escapes.
For example if you want to write the path of a file in Windows(for an os.walk for example) you would do it like this:
"d:\\projects\\re\\p1\\v1\\pjName\\log\\"
Or you could do this(the F# way):
#"d:\projects\re\p1\v1\pjName\log\"
The second variant looks much more clear and pleasing to the eye. Is there something of the sort in python? The documentation doesn't seem to have anything regarding that.
I am working in Python 3.6.3.
There are: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals
You can use r prefix.
https://docs.python.org/2.0/ref/strings.html
TL;DR use little r
myString = r'\n'
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:
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