Traling junk in string.atof (RE: array constructor)

Fredrik Lundh effbot at telia.com
Mon Feb 28 08:15:20 EST 2000


Tom Holroyd <tomh at po.crl.go.jp> wrote:
> I just thought it would make sense for a function _called_ atof() to
> _behave_like_ the POSIX function atof(), which converts the initial
> portion of a string only -- a behavior which most programmers that use
> atof() are well aware of (and even (gosh) use).

arguing that Python's standard functions should silently
ignore errors won't get you anywhere ;-)

(besides, atof is not a POSIX function, it's an ANSI C
function, and Python's not ANSI C).

rolling your own atof isn't that hard, though:

    import re

    def atof(s, p=re.compile(r"\s*(\d*(.\d*)?)")):
        try:
            return float(p.search(s).group(1))
        except (ValueError, AttributeError):
            return 0.0

    >>> atof("123.456,789")
    123.456
    >>> atof("  123.456  ")
    123.456
    >>> atof("glurk")
    0.0

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list