Python – Convert String to Int in Python

How to Convert String to int in Python Language?

Python is a popular high-level programming language and I think that many of you have encountered a problem with the conversion from string to int in Python.

There are two ways to transform a string to a int:

  1. Manual conversion. This method is harder because we ourselves should write the functions.
  2. The second is using built-in functions.

Manual conversion

An example of custom function of conversion from string to int in Python.

Output:String To Int in Python custom function

Description of the program

The function char2decBase converts char c to decimal number in base numberBase.

The function string2int converts the stringNumber to int number in base numberBase. The base range is from 2 till 36.

  1. Check if the string is not empty
  2. Check if a number is within a range [2, 36]
  3. Check the sign
  4. The String to int in base 10 conversion loop
  5. Returns the result, if the number is negative then change the sign of the number

Convert string to int in Python using the int() function

The built-in function to convert from string to int in Python is int().



x – number or the string representation of an integral number.
base – optional parameter and is a number (from 2 to 36) that represents the numeral system to be used.

Return value

This function returns an integer object constructed from a number or string x, or return 0 (zero) if no arguments are given.


  • In case if x is floating point number, the conversion truncates towards zero.
  • The function returns a long object instead in case if the argument is outside the integer range


Output:String To Int in Python int() function


ValueError in case if string or base are invalid.

2. Built-in Functions — Python 2.7.12 documentation
Execute Python Online
Python (programming language) – Wikipedia, the free encyclopedia

Leave a Reply

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