Check if a string is hexadecimal

后端 未结 11 1488
说谎
说谎 2020-12-13 06:14

I know the easiest way is using a regular expression, but I wonder if there are other ways to do this check.

Why do I need this? I am writing a Python script that re

11条回答
  •  孤城傲影
    2020-12-13 06:46

    (1) Using int() works nicely for this, and Python does all the checking for you :)

    int('00480065006C006C006F00200077006F0072006C00640021', 16)
    6896377547970387516320582441726837832153446723333914657L
    

    will work. In case of failure you will receive a ValueError exception.

    Short example:

    int('af', 16)
    175
    
    int('ah', 16)
     ...
    ValueError: invalid literal for int() with base 16: 'ah'
    

    (2) An alternative would be to traverse the data and make sure all characters fall within the range of 0..9 and a-f/A-F. string.hexdigits ('0123456789abcdefABCDEF') is useful for this as it contains both upper and lower case digits.

    import string
    all(c in string.hexdigits for c in s)
    

    will return either True or False based on the validity of your data in string s.

    Short example:

    s = 'af'
    all(c in string.hexdigits for c in s)
    True
    
    s = 'ah'
    all(c in string.hexdigits for c in s)
    False
    

    Notes:

    As @ScottGriffiths notes correctly in a comment below, the int() approach will work if your string contains 0x at the start, while the character-by-character check will fail with this. Also, checking against a set of characters is faster than a string of characters, but it is doubtful this will matter with short SMS strings, unless you process many (many!) of them in sequence in which case you could convert stringhexditigs to a set with set(string.hexdigits).

提交回复
热议问题