Writing a string.ishex function

Albert van der Horst albert at spenarnc.xs4all.nl
Fri Jan 22 17:00:54 CET 2010

In article <mailman.924.1263494171.28905.python-list at python.org>,
MRAB  <python at mrabarnett.plus.com> wrote:
>D'Arcy J.M. Cain wrote:
>> On Thu, 14 Jan 2010 07:52:58 -0800 (PST)
>> chandra <chyavana at gmail.com> wrote:
>>> Folks,
>>> I am new to Python and could not find a function along the lines of
>> Welcome.
>>> string.ishex in Python. There is however, a string.hexdigits constant
>>> in the string module. I thought I would enhance the existing modlue
>>> but am unsure how I should go about it. Specifically, I have attempted
>>> this much:
>> You should always test code before posting and post the exact code that
>> you tested.
>>> ---cut---
>>> #! /usr/bin/python
>>> # -*- coding: utf-8 -*-
>>> import string
>>> def ishex(string):
>> Bad idea to name your variable after a module.  This function fails
>> because of that.
>>>     ishex = False
>>>     for i in strdef ishex(sing:
>>>         if i in string.hexdigits:
>>>             ishex = True
>>>         else:
>>>             ishex = False
>>>             break
>>>     return ishex
>> After renaming the variable this works but you can simplify it.
>>> ---cut---
>> Just return False once you find a non-hex digit.
>> def ishex(s):
>>   for c in s:
>>     if not c in string.hexdigits: return False
>>   return True
>> And here are your unit tests.  Every line should print "True".
>> print ishex('123') is True
>> print ishex('abc') is True
>> print ishex('xyz') is False
>> print ishex('0123456789abcdefABCDEF') is True
>> print ishex('0123456789abcdefABCDEFG') is False
>Don't use 'is', use '=='.
>BTW, ishex('') should return False.

You are very wrong. Not with the above statement, but
the very act of issuing a statement like that is wrong.

The OP didn't specify ishex().
In absence of a specification, border cases are not defined.

If the specification was:
   any character of string s must be a hex character

then ishex('') should return True.

If the specification was:
   the string must represent a hex number

then ishex('') should probably return False.

I can imagine a specification where it is appropriate to
throw an exception for an empty string.
This is also the safest thing to do, if there is the slightest

So the correct behaviour is:
"Please mister customer, what exactly did you have in mind?"

Groetjes Albert

Economic growth -- being exponential -- ultimately falters.
albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst

More information about the Python-list mailing list