Transforming a str to an operator

Duke Normandin dukeofperl at ml1.net
Fri Aug 28 08:34:08 EDT 2009


On Thu, 27 Aug 2009, Stephen Hansen wrote:

> >
> > num1 = raw_input('Enter the first number: ')
> > num2 = raw_input('Enter the second number: ')
> > op = raw_input('Select one of the following [+-*/]: ')
> > print 'The answer is: ', int(num1), eval(op), int(num2)
> >                                    ^^^^^^^^
> >
> > How do I convert the contents of "op" from a string to an actual
> > arithmetic operator? eval() does not seem to be the answer. TIA!
> >
>
> You could eval(num1+op+num2), but it'd be safer to do:
>
> import operator
> operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/":
> operator.div}
> fn = operators[op]
> print "The answer is:", fn(int(num1), int(num2))
>
> Its best to avoid eval when possible :)
>
> --S
>

In *any* language "eval" is dangerous, so your second example would
also be my choice. Thanks for the clue.

BTW, I hunted hi-n-lo for something that would address my question at
http://docs.python.org. I obviously didn't have much luck. Something
about those docs that is confusing....
-- 
duke



More information about the Python-list mailing list