strings
Peter Otten
__peter__ at web.de
Thu Sep 4 03:25:03 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.
import locale
locale.setlocale(locale.LC_ALL, ("en", None))
def strtofloat(s):
try:
return locale.atof(s)
#return float(s.replace(",", ""))
except ValueError:
return 0.0
for s in "a 0 12 123.4 12,345.67 12,24a".split():
print s, "->", strtofloat(s)
Output:
a -> 0.0
0 -> 0.0
12 -> 12.0
123.4 -> 123.4
12,345.67 -> 12345.67
12,24a -> 0.0
Peter
More information about the Python-list
mailing list