I'm Sure There's A Better Way
Alex Martelli
aleaxit at yahoo.com
Sat Jul 7 03:38:20 EDT 2001
"Tim Daneliuk" <tundra at tundraware.com> wrote in message
news:3B465858.CB7F38E8 at tundraware.com...
> 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"
These specs seem to be equivalent to:
optional: -
one or more digits
optional: . followed by two digits
end of string
This is very easy to express as a Regular Expression:
r'-?\d+(\.\d\d)?$'
So one function to check any string to see if it satisfies
this pattern is:
def isDollar(astring):
import re
return re.match(r'-?\d+(\.\d\d)?$', astring)
Alex
More information about the Python-list
mailing list