string.atoi in Python

In this tutorial, we will learn about string.atoi in Python and how it can be used in various situations.

About string.atoi in Python

Atoi stands for ASCII to Integer Conversion and can be used for converting ASCII values or string values to type int.

The string.atoi has been replaced by simply Typecasting the String into Integer. Also, note that atoi() is still available in C programming language.

Syntax in C:    int atoi(constant string)

Following is an example if you try to use string.atoi in Python version 3.

import string

value = string.atoi

There will be no output to this code and it will produce an error. It will show:

AttributeError: module 'string' has no attribute 'atoi'

Code: string.atoi

Following is a code if you want to use atoi in Python 3.

def atoi(str):
    resultant = 0
    for i in range(len(str)):
        resultant = resultant * 10 + (ord(str[i]) - ord('0'))        #It is ASCII substraction 

    return resultant

str = input("Enter string to be converted")
sum = atoi(str) + 10000  #To show that it has been coverted to type int


Enter string to be converted





  • We have created a function atoi to convert the string to type int.
  • The ord() method returns an integer representing Unicode point for the given Unicode character.
  • (ord(str[i]) – ord(‘0’)) is simple ASCII conversion where ord(‘0’) is 47.
  • Add any number to the value returned by atoi().
  • No error shows that atoi() works properly.

Note that is is a case for only Positive Numbers. Try for Negative Numbers yourself.

If you are unable able to do it or have any doubts ask about it in the comments.

You can also read about: string.hexdigits in Python and Python Program to Compute Euclidean Distance

Leave a Reply

Your email address will not be published. Required fields are marked *