hex check

Steven Taschuk staschuk at telusplanet.net
Wed Jul 16 04:58:39 EDT 2003


Quoth Ruslan Spivak:
> Does anybody have a hint how to check if input hex number is in correct 
> hex format?

It's not entirely clear what you mean by "correct hex format".

If you mean "contains only the characters 0-9, a-f, and A-F", then
here's three ways:

    # 1
    import re
    def ishex(s):
        return re.match('^[0-9a-fA-F]*$', s) is not None

    # 2
    import string
    def ishex(s):
        for character in somestring:
            if character not in string.hexdigits:
                return False
        else:
            return True

    # 3
    import string
    def ishex(s):
        return s.strip(string.hexdigits) == ''

But I wonder why you want to bother checking this explicitly.
Consider these implementations (which are not actually
functionally equivalent to the previous three -- details left as
an exercise):

    # 4
    def ishex(s):
        try:
            int(s, 16)
        except ValueError:
            return False
        else:
            return True

    # 5
    import binascii
    def ishex(s):
        try:
            binascii.unhexlify(s)
        except TypeError:
            return False
        else:
            return True

Presumably, if the string *is* in correct hex format, you'll want
to convert it to an int or a byte string or something.  Why not
just do whatever it is you want to do and catch the possible
exception, as these implementations illustrate?

-- 
Steven Taschuk             "The world will end if you get this wrong."
staschuk at telusplanet.net     -- "Typesetting Mathematics -- User's Guide",
                                 Brian Kernighan and Lorrinda Cherry





More information about the Python-list mailing list