[Tutor] int("10**6")

Steven D'Aprano steve at pearwood.info
Wed Aug 1 10:55:34 CEST 2012


On Wed, Aug 01, 2012 at 01:37:00AM -0700, Albert-Jan Roskam wrote:
> Hi 
> I want the user to be able to specify "10**6" as arguments. How can I cast this string value (it's from sys.argv) to an int value?.
> Simply doing int("10**6") won't work. The code below works, but seems overly complicated.

Is your intention to support arbitrary arithmetic? E.g. what happens if 
the user provides "23.45 + -17.9**5.3e2 * log(0.023 + 9.31)/3" ?

If you want a full blown arithmetic parser, you will need to write one. 
It's not as hard as you might think, but neither is it trivial.

If you're satisfied with a *simple* arithmetic parser, you can try 
these:

http://effbot.org/zone/simple-iterator-parser.htm
http://effbot.org/zone/simple-top-down-parsing.htm

As an alternative, if you like living dangerously and don't mind having 
other people shouting at you, you can use eval. But BEWARE: you are 
opening yourself up to all sorts of nasty security vulnerabilities if 
you do so. But if this script is for your own personal use, it is worth 
considering.


If all you want is to support arguments of the form "INT ** INT", that's 
easy:

def eval_power(argument):
    if "**" in argument:
        a, b = argument.split("**", 1)
        a = a.strip()  # ignore whitespace
        b = b.strip()
        a = int(a)  # or float if you prefer
        b = int(b)
        return a**b
    else:
        return int(argument)  # or raise an error?

Now just call that function on each of your arguments, and you're done.



-- 
Steven


More information about the Tutor mailing list