Check if a string is hexadecimal

后端 未结 11 1473
说谎
说谎 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:26

    Most of the solutions proposed above do not take into account that any decimal integer may be also decoded as hex because decimal digits set is a subset of hex digits set. So Python will happily take 123 and assume it's 0123 hex:

    >>> int('123',16)
    291
    

    This may sound obvious but in most cases you'll be looking for something that was actually hex-encoded, e.g. a hash and not anything that can be hex-decoded. So probably a more robust solution should also check for an even length of the hex string:

    In [1]: def is_hex(s):
       ...:     try:
       ...:         int(s, 16)
       ...:     except ValueError:
       ...:         return False
       ...:     return len(s) % 2 == 0
       ...: 
    
    In [2]: is_hex('123')
    Out[2]: False
    
    In [3]: is_hex('f123')
    Out[3]: True
    

提交回复
热议问题