NEWBIE: ishexdigit revisited

engsolnom at ipns.com engsolnom at ipns.com
Mon Dec 29 17:36:01 EST 2003


After looking at the suggestions for a ishexdigit method, (thanks
again), I decided on the following, partly because I don't have to
import string, and I believe it's pretty readable by Python newbies,
which we (including myself) have at work:

def ishexdigit(sx):
    ix = 0
    for cx in sx:
        ix += 1
        if not cx in '0123456789abcdefABCDEF': return 0
    if ix % 2 == 0: return 1
    else: return 'Extra nibble'

# Try it out:

sx = '0123abcDEF'       # 5 bytes
print ishexdigit(sx)
if ishexdigit(sx):
    print 'All hex'
else:
    print 'Not hex'

sx = 'S123abcDEF'       # The 'S' is not hex
print ishexdigit(sx)
if ishexdigit(sx):
    print 'All hex'
else:
    print 'Not hex'

sx = '123abcDEF'        # 4 bytes plus a nibble
print ishexdigit(sx)
if ishexdigit(sx):
    print 'All hex'
else:
    print 'Not hex'

Results:

1
All hex

0
Not hex

Extra nibble
All hex

Notice that the user is warned (if he/she cares to be), that the
string isn't on byte boundries.

Norm





More information about the Python-list mailing list