In this tutorial, we will see how to Python String to int conversion. Converting one type to another type is called type casting or type coercion.
Python String to int Conversion :
Python provided an inbuilt function called int() to convert any convertible type to int. We can use this function to convert values from other types to int.
>>> int("150") 150
Note: If we want to convert str type to int type, the string should contain only integral values and should be specified in base-10 format otherwise it will throw error like below.
>>> int("15.50") Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> int("15.50") ValueError: invalid literal for int() with base 10: '15.50'
floating point String to int :
If we really want to convert a floating point string to int, first floating point string should be converted to float type and then float type should be converted to int.
>>> i = float("10.5") >>> int(i) 10
Boolean to int conversion :
In Python booleans were represented with numbers, True represents to “1” and False represents to “0”. So that If we want to convert bool to int the corresponding numbers (1 or 0) will be taken like below.
>>> int(True) 1 >>> int(False) 0
Note : We can convert from any type to int except complex types and names. The example below syntax is invalid.
>>> int(10.2j) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> int(10.2j) TypeError: can't convert complex to int >>> int("Hello") Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> int("Hello") ValueError: invalid literal for int() with base 10: 'Hello'
Happy Learning 🙂