tags:

views:

2214

answers:

3

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.

+11  A: 

int("0x123", 0)

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

Hein
It's just the way int is implemented in Python - it assumes decimal unless you explicitly tell it to guess by passing 0 as the radix.
David Zaslavsky
+2  A: 

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)
S.Lott
+3  A: 

Base 16 to 10 (return an integer):

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

Base 10 to 16 (return a string):

>>> hex(291)
'0x123'
Selinap