Convert a Python String to int

In Python, we can use int() method to convert a String to int.


Python int() method to convert a String to int
When programming, there are times you need to convert values between types in order to manipulate values in a different way. Python defines type conversions directly to convert one data type to another which is useful in day to day and competitive development.

Python String to int

A String is a sequence of one or more characters. Integers are whole numbers. In other words, they have no fractional component. In Python, Strings can be converted to Int by using the built-in function int() method . Syntax
Base specifies the base in which string is if data type is string. example
str = "111" num = int(str) print(num) num = num +1 print(num) print("Type of str : " , type(str)) print("Type of num : " , type(num))
111 112 Type of str : <class 'str'> Type of num : <class 'int'>

Number Bases

A number base is the number of digits or combination of digits that a system of counting uses to represent numbers . A base can be any whole number greater than 0. The most commonly used number system is the decimal system, commonly known as base 10 .

String to int from different base

The method int(str,base) , second argument is base. If the string you want to convert into int belongs to different number base other that base 10, you can specify the base for conversion. But remember that the output integer is always in base 10 .
str = "111" print(str) #convert from base 10 print("Base 10 to base 10: " , int(str)) #convert from base 8 print("Base 8 to base 10: " , int(str, base=8)) #convert from base 6 print("Base 6 to base 10: " , int(str, base=6))
111 Base 10 to base 10: 111 Base 8 to base 10: 73 Base 6 to base 10: 43


You can convert a Python string to an int by using ast.literal_eval() . This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions , for example involving operators or indexing.

Handling malformed strings

Some strings do not represent valid numbers . If you try to convert such a string, you will get an exception:
Python: invalid literal for int() with base 10

How to fix?

You can solve this invalid literal for int() with base 10 by using Python isdigit() method to check whether the value is number or not. The returns True if all the characters are digits, otherwise False.
num = "55.55" if num.isdigit(): print(int(num)) else: print("String value is not a digit : " , num)
String value is not a digit : 55.55