-6

How can I remove ' from the string '/' and use it for division in Python?

For example:

a='/'
b=6
c=3

bac

The answer should be 2.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247

3 Answers3

6

You can get the built-in operators as functions from the operator module:

import operator

a = operator.div
b = 6
c = 3

print a(b, c)

If you want to get the correct operator by the symbol, build a dict out of them:

ops = {
    "/": operator.div,
    "*": operator.mul,
    # et cetera
}

a = ops["/"]
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
4

Python has an eval() function that can do this:

a = "/"
b = "6"
c = "3"
print eval(b + a + c)

However, please note that if you're getting input from a remote source (like over a network), then passing such code to eval() is potentially very dangerous. It would allow network users to execute arbitrary code on your server.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
3

There are no single quotes in the variable a. Python just uses these to denote a represents a string. b and c represent ints and don't have the single quotes. If you ensure all of these variables are strings, you can join() them together:

>>> a='/'
>>> b=6
>>> c=3
>>> bac = ''.join(str(x) for x in (b, a, c))
>>> bac
'6/3'

See how there are single quotes at the beginning and end of the string.

You could then use eval() (with caution) to perform the division:

>>> eval(bac)
2

Related: Is using eval in Python a bad practice?

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247