Writing a string.ishex function
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Jan 14 19:53:51 EST 2010
On Thu, 14 Jan 2010 18:36:12 +0000, MRAB wrote:
>> 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 '=='.
I beg to differ. In this case, since ishex is intended to return True or
False and not 1.0 or Decimal(0), the correct test for the purposes of
unit-testing is the identity test, not equality.
However, for the purposes of *displaying* the result, rather than saying:
print ishex('123') is True
one should obviously say:
print ishex('123') is True is True
No, wait, that should be:
print ishex('123') is True is True is True
No wait, this is better:
print ishex('123') is True is True is True is True
*wink*
Seriously, just say print ishex('123'). It already returns True or False,
you don't need to compare it to True or False to get a True or False
answer.
> BTW, ishex('') should return False.
Only if you want to be inconsistent with other isFoo string functions:
>>> ''.isalpha()
False
>>> ''.isupper()
False
>>> ''.islower()
False
>>> ''.isspace()
False
Also, if ishex(s) returns True, then a reasonable person will expect that
calling int(s, 16) should succeed. But if s is the empty string, it will
fail.
--
Steven
More information about the Python-list
mailing list