Writing a string.ishex function
MRAB
python at mrabarnett.plus.com
Thu Jan 14 13:36:12 EST 2010
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.
More information about the Python-list
mailing list