Writing a string.ishex function

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Thu Jan 14 15:26:51 EST 2010


On 08:15 pm, darcy at druid.net wrote:
>On 14 Jan 2010 19:19:53 GMT
>Duncan Booth <duncan.booth at invalid.invalid> wrote:
>> > ishex2 = lambda s: not(set(s)-set(string.hexdigits))     # Yours
>> > ishex3 = lambda s: not set(s)-set(string.hexdigits)      # Mine
>> >
>> > I could actually go three better:
>> >
>> > ishex3=lambda s:not set(s)-set(string.hexdigits)
>>
>>But none of those pass your own "ishex('') should return False" test.
>
>Good point.  Obviously a unit test was missing.
>
>Of course, all this is good clean fun but I wonder how useful an ishex
>method really is.  Personally I would tend to do this instead.
>
>try: x = isinstance(s, int) and s or int(s, 0)
>except ValueError: [handle invalid input]
>
>IOW return the value whether it is a decimal string (e.g. "12"), a hex
>string (e.g. "0xaf") or even if it is already an integer.  Of course,
>you still have to test for '' and None.

Still missing some unit tests.  This one fails for 0.  Spend a few more 
lines and save yourself some bugs. :)

Jean-Paul



More information about the Python-list mailing list