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 reads text messages (SMS) from a SIM card. In some situations, hex messages arrives and I need to do some processing for them, so I need to check if a received message is hexadecimal.
When I send following SMS:
utf-16 big endian encoding
from binascii import unhexlify # unhexlify is another name of a2b_hex
mystr = "00480065006C006C006F00200077006F0072006C00640021"
>> u'Hello world!'
(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
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
'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
False based on the validity of your data in string
s = 'af' all(c in string.hexdigits for c in s) True s = 'ah' all(c in string.hexdigits for c in s) False
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