Writing a string.ishex function
Christian Heimes
lists at cheimes.de
Thu Jan 14 13:07:29 EST 2010
Iain King wrote:
> better would be:
> def ishex(s):
> for c in s:
> if c not in string.hexdigits:
> return False
> return True
Even more elegant and probably a faster solutions:
---
from string import hexdigits
hexdigits = frozenset(hexdigits)
def ishex(s):
return set(s).issubset(hexdigits)
---
If you are also interested in the integer value of a hex string:
---
def gethex(s):
try:
return int(s, 16)
except ValueError:
return None
---
Check for "gethex(s) is not None" to see if s is a hex string.
Christian
More information about the Python-list
mailing list