NEWBIE: What's the instance name?

Bengt Richter bokr at oz.net
Mon Dec 29 01:54:58 EST 2003


On 28 Dec 2003 21:46:36 -0800, dw-google.com at botanicus.net (David M. Wilson) wrote:

>engsolnom at ipns.com wrote...
>
>> Also, if I have a string 4 chars long, representing two bytes of hex,
>> how can I *validate* the string as a *legal* hex string?
>> 
>> isdigit works until string = '001A', for example
>> isalnum works, but then allows 'foob'
>> 
>> Is there a 'ishexdigit'? I could parse the string, but that seems
>> "un-Pythonish"
>
>
>Have you considered using the int() builtin? Here is an example:
>
>    def is_hex(n):
>        '''
>        Return truth if <n> can be converted as hexadecimal
>        from a string.
>        '''
>
>        try:
>            int(n, 16)
>            return True
>
>        except ValueError:
>            return False

But that will accept '0x55' which I doubt the OP will like ;-)

If you don't care about speed,
(Not tested beyond what you see ;-)

 >>> def isHex(n): return bool(min([c in '0123456789ABCDEFabcdef' for c in n]))
 ...
 >>> isHex('005')
 True
 >>> isHex('0x5')
 False
 >>> isHex('0123456789ABCDEFabcdef')
 True
 >>> isHex('0123456789ABCDEFabcdefg')
 False

Probably faster, depending on the C implementation:

 >>> def isHex(s):
 ...     return not s.translate(
 ...         '................................'
 ...         '................................'
 ...         '................................'
 ...         '................................'
 ...         '................................'
 ...         '................................'
 ...         '................................'
 ...         '................................',
 ...         '0123456789ABCDEFabcdef')
 ...
 >>> isHex('0123456789abcdefABCDEF')
 True
 >>> isHex('0123456789abcdefABCDEFg')
 False
 >>> isHex('0x5')
 False
 >>> isHex('005')
 True



Regards,
Bengt Richter




More information about the Python-list mailing list