strings
Alex Martelli
aleax at aleax.it
Thu Sep 4 03:51:56 EDT 2003
Scribe wrote:
> Hi
> Somewhat new to Python and would appreciated some help in selecting the
> best builtins to achieve what I want.
> I pass a string to a function, it is either
> empty
> spaces
> alpha and digits
> or
> a decimal ie. 5,789.88
> if it is a decimal I want to return the number without the commer any
> others return 0.
> Should be simple or maybe I am.
> Any help apreciated.
def scribefun(astring):
try: return int(float(astring.replace(',','')))
except ValueError: return 0
This assumes you want to return e.g. 5789 for '5,789.88', i.e.,
an integer truncating the "decimal" (otherwise omit the int()).
Only possible issue is if the "alpha and digits" specifically
include an 'e' as the only "alpha", which builtin float() would
take as an indication of exponential notation; so for example
this would return 100, not 0, for '1e2'. If this is a problem
(unclear from your specs) it ain't all that hard to fix of course.
Alex
More information about the Python-list
mailing list