Python Forum

Full Version: checking for valid hexadecimal digits
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a string that may be a valid AMI ID in AWS context. that would be "ami-" followed by 17 hexadecimal digits. checking the prefix and length is direct enough. i was hoping there was a str method like there is isdecimal() for decimal digits, but there isn't. so i am using my own function like:
def ishex(s):
    try:
        n = int(s,16)
        return True
    except ValueError:
        return False
i was wondering if there was something better in Python so i can ditch this little function.
Seems fine. Especially if you're already checking for length first, there won't really be any performance issues.

There is a minor edge case where this would return True for "0xA", while the "x" is not a hexadecimal digit.

If you had a huge string, then converting it into an int takes work that isn't necessary. In the large case, I'd probably use the re engine to look for non-hexadecimal digits. A string with one million hex digits takes a bit of time to go through int(), while the re.search test is very fast.

def ishex(s):
    return not re.search(r"[^A-F0-9]", s)
Could also do a set comparison which works quickly on large strings:

def ishex(s):
    return not set(s) - set("ABCDEF0123456789")
a huge str of hexadecimal would be the absurd case. i can't envision it ever happening in realistic cases. these values will be user input and responses from AWS. a few hundred digits because someone was banging on the 'f' key to get it to quit bouncing and accidentally hit return is probably the worst case. a len() check should be good enough.

ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff