Math operations from string
Warning: this way is not a safe way, but is very easy to use. Use it wisely.
Use the eval function.
print eval('2 + 4')
Output:
6
You can even use variables or regular python code.
a = 5
print eval('a + 4')
Output:
9
You also can get return values:
d = eval('4 + 5')
print d
Output:
9
Or call functions:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
a = 20
b = 10
print eval('add(a, b)')
print eval('subtract(a, b)')
Output:
30
10
In case you want to write a parser, maybe instead you can built a python code generator if that is easier and use eval to run the code. With eval you can execute any Python evalution.
Why eval is unsafe?
Since you can put literally anything in the eval, e.g. if the input argument is:
os.system(‘rm -rf /’)
It will remove all files on your system (at least on Linux/Unix).
So only use eval when you trust the input.
How to do math operations with string?
You could write something like:
def parse_exp(s):
return eval(s.replace('x','*'))
and expand for whatever other exotic symbols you want to use.
To limit the risks of eval you can also eliminate bad characters:
import string
good = string.digits + '()/*+-x'
def parse_exp(s):
s2 = ''.join([i for i in s if i in good])
return eval(s2.replace('x','*'))
Edit: additional bonus is that the in-built eval
function will take care of things like parenthesis and general calculation rules :)
Edit 2: As another user pointed out, eval
can be dangerous. As such, only use it if your code will ever only run locally
Math operations from string using Javascript
It's a little hacky, but you can try something like this:
var eqs = [
'1+2*3*4+1+1+3',
'1+2*3*400+32/2+3',
'-5+2',
'3*-2',
];
for(var eq in eqs) { console.log(mdas(eqs[eq])); }
function mdas(equation) {
console.log(equation);
var failsafe = 100;
var num = '(((?<=[*+-])-|^-)?[0-9.]+)';
var reg = new RegExp(num + '([*/])' + num);
while(m = reg.exec(equation)) {
var n = (m[3] == "*") ? m[1]*m[4] : m[1]/m[4];
equation = equation.replace(m[0], n);
if(failsafe--<0) { return 'failsafe'; }
}
var reg = new RegExp(num + '([+-])' + num);
while(m = reg.exec(equation)) {
var n = (m[3] == "+") ? 1*m[1] + 1*m[4] : m[1]-m[4];
equation = equation.replace(m[0], n);
if(failsafe--<0) { return 'failsafe'; }
}
return equation;
}
Convert a string with arithmetic operation to an interger in python
You're looking for eval
:
>>> a = eval('4 * 5')
>>> a
20
>>> type(a)
<type 'int'>
Caveat: BE CAREFUL WITH THIS. eval()
will evaluate mathematical expressions like this one, but will also execute any valid python code it's given. For example,
>>> eval( 'type(a)' )
<type 'int'>
Performing math operation when operator is stored in a string
I don't recommend this but is funny. in java6
String op = '+';
int first= 10;
int second = 20;
ScriptEngineManager scm = new ScriptEngineManager();
ScriptEngine jsEngine = scm.getEngineByName("JavaScript");
Integer result = (Integer) jsEngine.eval(first+op+second);
go with the switch, but remember to convert the string operator to char as switch don't works with strings yet.
switch(op.charAt(0)){
case '+':
return first + second;
break;
// and so on..
How to perform math operation on numbers in string of python
This might help. Use the isalpha method to remove all alpha chars and the use eval
Ex:
s = "1abc0+5*1hv0"
s = "".join([i for i in s if not i.isalpha()])
print eval(s)
Output:
60
How to use math operators with strings?
int RTPower = Int32.Parse(powerTextBox.Text);
or for decimal values
decimal RTPower = Decimal.Parse(powerTextBox.Text);
You need to convert the value from a string to an int.
Also, I assume you are new to c# - my advice would be to avoid using var and explicitly declare your variables. It will make things clear and easier for you to learn and understand.
Related Topics
Stopping a Thread After a Certain Amount of Time
Target Wsgi Script Cannot Be Loaded as Python Module
Uploading Multiple Files with Flask
Why Is Using Thread Locals in Django Bad
Generating File to Download with Django
Deleting Multiple Columns Based on Column Names in Pandas
Is It Pythonic to Import Inside Functions
Matplotlib: How to Prevent X-Axis Labels from Overlapping
Most Pythonic Way to Interleave Two Strings
No Module Named 'Pandas._Libs.Tslibs.Timedeltas' in Pyinstaller
Pythonic Way to Create Union of All Values Contained in Multiple Lists
Overloaded Functions in Python
Executing Command Line Programs from Within Python
How to Plot a Confusion Matrix
How to Access a File's Properties on Windows
How to Concatenate Two Dataframes Without Duplicates