how to parse hex or decimal int in Python

Viewed 50795

I have a string that can be a hex number prefixed with "0x" or a decimal number without a special prefix except for possibly a minus sign. "0x123" is in base 16 and "-298" is in base 10.

How do I convert this to an int or long in Python?

I don't want to use eval() since it's unsafe and overkill.

5 Answers
int("0x123", 0)

(why doesn't int("0x123") do that?)

Base 16 to 10 (return an integer):

>>> int('0x123', 16)
291

Base 10 to 16 (return a string):

>>> hex(291)
'0x123'

Something like this might be what you're looking for.

def convert( aString ):
    if aString.startswith("0x") or aString.startswith("0X"):
        return int(aString,16)
    elif aString.startswith("0"):
        return int(aString,8)
    else:
        return int(aString)
Related