using split for a string : error

Hans Mulder hansmu at
Fri Jan 25 15:31:21 CET 2013

On 25/01/13 15:04:02, Neil Cerutti wrote:
> On 2013-01-25, Oscar Benjamin <oscar.j.benjamin at> wrote:
>> On 24 January 2013 11:35, Chris Angelico <rosuav at> wrote:
>>> It's usually fine to have int() complain about any
>>> non-numerics in the string, but I must confess, I do sometimes
>>> yearn for atoi() semantics: atoi("123asd") == 123, and
>>> atoi("qqq") == 0. I've not seen a convenient Python function
>>> for doing that. Usually it involves manually getting the
>>> digits off the front. All I want is to suppress the error on
>>> finding a non-digit. Oh well.
>> I'm interested to know what the situations are where you want
>> the behaviour of atoi().
> Right. atoi is no good even in C. You get much better control
> using the sprintf family.

I think you meant sscanf.

It's true that sscanf gives you more control.  That being said,
sometimes the one option atoi gives you, just happens to be what
you need.

> int would need to return a tuple of the
> number it found plus the number of characters consumed to be more
> useful for parsing.
>>>> intparse("123abc")
> (123, 3)
> But that would make it might inconvenient for general use.

If the new function is nameed intparse, and the existing int
function remains available, then most use cases would be served
by int, and intparse would be available as a building block for
other use cases.  For example atoi could be defined as:

def atoi(s): return intparse(s)[0]

intparse("xyz") should return (0, 0), and leave it to the caller
to decide whether a ValueError shoud be raised.

-- HansM

More information about the Python-list mailing list