
In this tutorial of Python Examples, we learned to convert a string value to an integer value, with the help of int() function. This function can take any Python data type as its parameter and return the corresponding integer value, as long as it is definable. In this example, we will convert Octal representation of a number in string, to integer. The built-in int () function in Python converts a string to its corresponding integer value. In this example, we will convert hexadecimal representation of a number in string, to integer.Ģ878742799 is of type: Example 4: Octal String to Int In this example, we will convert binary representation of a number in string, to integer. When you call the int (), you create a new integer object.

Here’s the int () constructor: int (x, base10) Note that int () is a constructor of the built-in int class. The int () accepts a string or a number and converts it to an integer. If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just pass the string to int (), which returns a decimal integer: >. Print('\nOutput', output, type(output), sep='\n') Run Introduction to the Python int () constructor. In this example, we will take a string in a, convert it to int using int(). Use try-catch Block The simplest way to try if a string variable will convert to an integer is to wrap the operation in a try-catch block. If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just pass the string to int (), which returns a decimal integer: >. Example 1: String to Int (Default Base Value) The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. In this tutorial, we shall go through some of the example programs that convert a string to integer.

In this quick and practical tutorial, youll learn how you can store integers using int and str as. int(s) #s is given stringĪs integer can be represented using different base values, and if the given string is a representation of an integer in a specific base value, we can pass both the string and base as arguments to int() function. There are several ways to represent integers in Python. Pass the string as argument to int() and it returns an integer value. To convert given value of string to integer in Python, call the int() built-in function.

