Transforming a str to an operator

Duke Normandin dukeofperl at ml1.net
Fri Aug 28 10:18:48 EDT 2009


On Thu, 27 Aug 2009, r wrote:

> On Aug 27, 10:52 pm, Duke Normandin <dukeofp... at ml1.net> wrote:
> > 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!
>
>
> Try this..
>
> >>> op = '+'
> >>> one = '1'
> >>> two = '2'
> >>> one+op+two
> '1+2'
> >>> eval(one+op+two)
> 3
>
>
> you could also use string formatting.

I see! Concatenate the strings within the "eval()" function. Of
course, it's prudent not to expose "eval" to the outside world. But
for learning purposes ....

Thanks for the input!
-- 
duke


More information about the Python-list mailing list