Transforming a str to an operator

r rt8396 at gmail.com
Fri Aug 28 06:08:54 CEST 2009


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.



More information about the Python-list mailing list