Writing a string.ishex function

Chris Rebert clp2 at rebertia.com
Thu Jan 14 12:07:47 EST 2010


On Thu, Jan 14, 2010 at 8:14 AM, Iain King <iainking at gmail.com> wrote:
> On Jan 14, 3:52 pm, chandra <chyav... at gmail.com> wrote:
>> Folks,
>>
>> I am new to Python and could not find a function along the lines of
>> 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:
>> ---cut---
>> #! /usr/bin/python
>> # -*- coding: utf-8 -*-
>>
>> import string
>>
>> def ishex(string):
>>     ishex = False
>>     for i in string:
>>         if i in string.hexdigits:
>>             ishex = True
>>         else:
>>             ishex = False
>>             break
>>     return ishex
>> ---cut---
>>
>> Can someone help me get further along please?
>>
>> Thanks.
>
> better would be:
> def ishex(s):
>    for c in s:
>        if c not in string.hexdigits:
>            return False
>    return True

Even more succinctly:

def ishex(s):
    return all(c in string.hexdigits for c in s)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list