I'm Sure There's A Better Way

Bengt Richter bokr at accessone.com
Sat Jul 7 15:09:05 CEST 2001


On 07 Jul 2001 00:40:01 GMT, Tim Daneliuk <tundra at tundraware.com>
wrote:

>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
>
>--
I think you could do it just checking for a full match
with a regular expression. Return 1 and 0 instead of 'yes' and 'no'
for more typical usage. The latter was just for interactive
readability :)

If you require a decimal to the left of the decimal point, you could
write
     mo = re.match(r'^-?\d+(\.\d\d)?$',num)
instead of the below

 >>> import re
 >>> def IsNum(num):
 ...     mo = re.match(r'^-?(\d*\.\d\d|\d+)$',num)
 ...     if mo and mo.group()==num: return 'yes'
 ...     return 'no'
 ...
 >>> IsNum('-123.456')
 'no'
 >>> IsNum('-123.45')
 'yes'
 >>> IsNum('-1.3.45')
 'no'
 >>> IsNum('-1.345')
 'no'
 >>> IsNum('-1345')
 'yes'
 >>> IsNum('.1345')
 'no'
 >>> IsNum('.13')
 'yes'
 >>> IsNum('-13')
 'yes'
 >>> IsNum('-1')
 'yes'
 >>> IsNum('-0')
 'yes'

Not thoroughly tested ;-)





More information about the Python-list mailing list