Wednesday, September 21, 2011

A real Python parse integer function

Is anyone else annoyed by the fact that int() in python is retarded and can't tell the difference between decimal, hex, and octal?

Your solution:

def parseint(val):
    if isinstance(val, int):
        return val
    if not isinstance(val, (unicode,str)):
        return None


    try:
        if val.startswith('0x'):
            return int(val, 16)
        if val.startswith('0'):
            return int(val, 8)
        return int(val)
    except ValueError:
        return None

Hope this helps someone.

No comments:

Post a Comment