Writing a string.ishex function
Steve Holden
steve at holdenweb.com
Thu Jan 14 12:06:23 EST 2010
chandra wrote:
> On Jan 15, 12:22 am, "D'Arcy J.M. Cain" <da... at druid.net> wrote:
>
>> 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
>>
>
> Thanks to Iain and to you.
>
> One further question: even though it is a single function, is there
> any way to convert it into a module? Can existing modules be enhanced
> with functions such as these? If not, how may I make my own module,
> called, say mystring? At present, I am saving the file as ishex.py and
> calling it after declaring
>
> from ishex import ishex
>
> Is there a more elegant way to integrate this function and make it
> available to other python scripts using the import mechanism?
>
Nope, that's about as elegant as it gets.
You can, of course, include it in a generic utility module and import
several things from that module - you aren't limited to defining a
single object in a module.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
More information about the Python-list
mailing list