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

R

Robbie

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
 
R

Raymond Hettinger

Robbie said:
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

int() should do the trick:
81


Raymond Hettinger
 
J

John Machin

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
 
B

Bengt Richter

I may be totally wrong but I believe there is a atoi in the strings
modules.
Easy to check:
Help on function atoi in module string:

atoi(s, base=10)
atoi(s [,base]) -> int

Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted.

Regards,
Bengt Richter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top