Writing a string.ishex function

C

chandra

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.
 
I

Iain King

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
 
D

D'Arcy J.M. Cain

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
 
C

chandra

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?

Thanks.

Chandra
 
S

Steve Holden

chandra said:
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
 
C

Chris Rebert

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
 
D

D'Arcy J.M. Cain

Even more succinctly:

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

I'll see your two-liner and raise you. :)

ishex = lambda s: all(c in string.hexdigits for c in s)
 
A

Arnaud Delobelle

D'Arcy J.M. Cain said:
I'll see your two-liner and raise you. :)

ishex = lambda s: all(c in string.hexdigits for c in s)

I'see your one-liner and raise you by four characters :eek:)

ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine

Notice that ishex2 is more accurate than ishex1. E.g.
ishex1(['abc', '123']) True
ishex2(['abc', '123'])
False
 
M

MRAB

D'Arcy J.M. Cain said:
You should always test code before posting and post the exact code that
you tested.


Bad idea to name your variable after a module. This function fails
because of that.


After renaming the variable this works but you can simplify it.



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.
 
M

MRAB

Arnaud said:
I'see your one-liner and raise you by four characters :eek:)

ishex1 = lambda s: all(c in string.hexdigits for c in s) # Yours
ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Mine
I raise you one character:

ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
ishex3 = lambda s: not set(s)-set(string.hexdigits) # Mine

I could actually go three better:

ishex3=lambda s:not set(s)-set(string.hexdigits)

:)
Notice that ishex2 is more accurate than ishex1. E.g.
ishex1(['abc', '123']) True
ishex2(['abc', '123'])
False
 
D

D'Arcy J.M. Cain

But none of those pass your own "ishex('') should return False" test.

Good point. Obviously a unit test was missing.

Of course, all this is good clean fun but I wonder how useful an ishex
method really is. Personally I would tend to do this instead.

try: x = isinstance(s, int) and s or int(s, 0)
except ValueError: [handle invalid input]

IOW return the value whether it is a decimal string (e.g. "12"), a hex
string (e.g. "0xaf") or even if it is already an integer. Of course,
you still have to test for '' and None.

Naturally this all depends heavily on the actual requirements. Perhaps
that's why there is no ishex method in the first place. Such a method
could wind up with more options than ls(1)
 
E

exarkun

But none of those pass your own "ishex('') should return False" test.

Good point. Obviously a unit test was missing.

Of course, all this is good clean fun but I wonder how useful an ishex
method really is. Personally I would tend to do this instead.

try: x = isinstance(s, int) and s or int(s, 0)
except ValueError: [handle invalid input]

IOW return the value whether it is a decimal string (e.g. "12"), a hex
string (e.g. "0xaf") or even if it is already an integer. Of course,
you still have to test for '' and None.

Still missing some unit tests. This one fails for 0. Spend a few more
lines and save yourself some bugs. :)

Jean-Paul
 
A

Arnaud Delobelle

MRAB said:
I raise you one character:

ishex2 = lambda s: not(set(s)-set(string.hexdigits)) # Yours
ishex3 = lambda s: not set(s)-set(string.hexdigits) # Mine

Aha! The Operator Precedence trick! I fold.
I could actually go three better:

ishex3=lambda s:not set(s)-set(string.hexdigits)

In this case, I'll go five better:

h=lambda s:not set(s)-set(string.hexdigits)

;-)
 
T

Terry Reedy

I'll see your two-liner and raise you. :)

ishex = lambda s: all(c in string.hexdigits for c in s)

This is inferior because the resulting function object has generic name
attribute '<lambda>' instead of the specific name 'ishax'.

Please do not push such inferior code on new programmers.

Terry Jan Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,236
Latest member
ShondaSchu

Latest Threads

Top