Writing a string.ishex function
D'Arcy J.M. Cain
darcy at druid.net
Thu Jan 14 11:22:54 EST 2010
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
--
D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves
http://www.druid.net/darcy/ | and a sheep voting on
+1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner.
More information about the Python-list
mailing list