Is there the same function in python as atoi() in C

John Machin sjmachin at lexicon.net
Sat Aug 2 00:47:13 EDT 2003


On Sat, 2 Aug 2003 11:51:54 +0800, "Robbie" <robbie_cao at msn.com>
wrote:

>Someone tell me,
>if not exist, how to write one with the same function?
>I have made a try, but there is no character type in python,
>so i failed, someone help me,
>thanks very much
>
>

General question: Have you read some of the tutorials?

Regarding your specific problem:

1. Think about it. A language without such a function would be utterly
useless.

2. There is a built-in function called int() -- look it up in the
manual.

3. Don't bother with the atoi() in the string module -- inspection of
..../Lib/string.py will tell you that it just calls int() anyway.

4. No character type? How would you like that, signed or unsigned or
implementation-defined? Python avoids that little chamber of horrors
and does rather well by using strings of length 1. Here's a rough
untested no-negative-allowed no-explicit-overflow-checking
base-10-only atoi() ...

def demo_atoi(astr):
    num = 0
    for c in astr:
        if '0' <= c <= '9':
            num  = num * 10 + ord(c) - ord('0')
        else:
            raise ValueError('demo_atoi argument (%s) contains
non-digit(s)' % astr)
    return num





More information about the Python-list mailing list