I'm Sure There's A Better Way
Tim Daneliuk
tundra at tundraware.com
Fri Jul 6 20:40:01 EDT 2001
I want a function to check a string to make sure it is a legitimate
dollar amount. Which means it follows these rules:
First character is numeric or "-"
At most, one "." is allowed and, if present, is followed by exactly two digits
All the remaining characters must be in the range "0" - "9"
I wrote the attached to check a string for these rules, but I can't help
wondering if my feeble newbie python coding isn't already better done
elswhere and/or using existing logic. Any ideas all? TIA.... Code follows -
# Check and see if passed string is a legit amount
def IsNum(num):
if num == "":
return FALSE
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."]
z = num.split(".")
if len(z) > 2: # At Most, only once decimal permitted.
return FALSE
if len(z) == 2:
if len(z[1]) != 2: # Exactly two digits must follow decimal
return FALSE
if (num[0] == '-') and (len(num) > 1): # 1st char can be sign if more chars follow
num = num[1:] # Drop sign for purposes of checking
for x in num: # Make sure all chars are legit digits
if not digits.count(x):
return FALSE
return TRUE
--
------------------------------------------------------------------------------
Tim Daneliuk
tundra at tundraware.com
More information about the Python-list
mailing list