0

How do I perform calculations with strings? Like suppose I have:

a=('/')
print(10, a, 5)

How do I get the answer as '2'? Because 10/5 is 2.

Saaheer Purav
  • 39
  • 3
  • 5
  • Does this answer your question? [Evaluate math equations from unsafe user input in Python](https://stackoverflow.com/questions/26505420/evaluate-math-equations-from-unsafe-user-input-in-python) – ChrisGPT was on strike Feb 01 '20 at 15:49
  • This Link is what you are looking for https://stackoverflow.com/questions/1740726/turn-string-into-operator – Samer Ayoub Feb 01 '20 at 15:51

3 Answers3

1

There are multiple ways to do this.

The most common way, I guess, is using the operator module and a map (dictionary) to turn your strings into operators, as the next example.

import operator

run_ops = {
  '+' : operator.add,
  '-' : operator.sub,
  '*' : operator.mul,
  '/' : operator.truediv,
  '%' : operator.mod,
  '^' : operator.xor,
}.get

print(run_ops('/')(10, 5))

Or go with lambdas:

run_ops= {'+': lambda x, y: x + y,
    '-': lambda x, y: x - y,
    # ...
    '/': lambda x, y: x / y
}

run_ops['/'] (10,5)

Cheers

epap
  • 39
  • 4
0

A nice method has been posted by epap.

However if you want to stick to the order of the expression where the "/", comes between the two numbers then one of the ways you can do it, is as below.

You can wrap (Number_1, "/", Number_2) and send it to a class and then print it. Something like below.

class Divide(object):

    def __new__(cls, a, symbol, b):
        result = None
        if symbol == "/":
            result = a/b        
        return result


print(Divide(5,"/",2))

This yields the below output

2.5
Amit
  • 2,018
  • 1
  • 8
  • 12
-2

You can use "eval" to evaluate expressions given as strings.

a = "/"
res = eval("10" + a + "5")
print(res)
andi8086
  • 394
  • 2
  • 9
  • 3
    `eval()` is a huge security risk if used on unknown input, and the kind of thing new programmers are likely to start using everywhere when they discover it. Please don't recommend using it without a very strong warning. It's almost never the right solution. – ChrisGPT was on strike Feb 01 '20 at 15:56
  • Never pass user input as argument to eval. Or even better forget that eval exists. – ElmoVanKielmo Feb 01 '20 at 15:58