Writing a string.ishex function

D'Arcy J.M. Cain darcy at druid.net
Thu Jan 14 15:15:07 EST 2010


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.

Naturally this all depends heavily on the actual requirements.  Perhaps
that's why there is no ishex method in the first place.  Such a method
could wind up with more options than ls(1)

-- 
D'Arcy J.M. Cain <darcy at druid.net>         |  Democracy is three wolves
http://www.druid.net/darcy/                |  and a sheep voting on
+1 416 425 1212     (DoD#0082)    (eNTP)   |  what's for dinner.



More information about the Python-list mailing list