Writing a string.ishex function

Iain King iainking at gmail.com
Thu Jan 14 11:14:33 EST 2010


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

Iain



More information about the Python-list mailing list