Read Python Interview Questions and Answers for Beginners and Experienced

Convert String to Integer in Python with example

In our Python Examples series of Python basics tutorials online, we learnt how to convert Integer to String in Python, In this post of Python programming tutorial, we will study that how we can convert String to Integer in Python.

 

Use of int() function

We can convert String to integer by using int() function of Python.

 

Syntax of int() function

Syntax of int() function in Python is

 

int(value, base_value)

 

  • int() is function name.
  • value is that variable whose value need to be converted in integer.
  • base_value is base value of integer to be converted, it could be >=2 and <=36. we will understand this by taking examples. base_value is optional.

 

Examples of converting String to Integer  in Python

In below, we will see some examples of Python String to Integer conversion.


# Python String to Integer example

age="10"

print ("type of age is",type(age))

num1=int(age)

print ("type of age is",type(num1), "and value is",num1 )

 

Output

type of age is <class 'str'>
type of age is <class 'int'> and value is 10

 

Explanation:

  • In above example, age is string variable with value 10.
  • When we apply int() function on String variable age, it convert the String value to integer value.
  • As, we did not put any base value to int() function, by default it takes  10 as base value.

 

Convert String to Integer with base 2 example


# Python String to Integer example

age="10"

print ("type of age is",type(age))

num1=int(age)

print ("type of age is",type(num1), "and value is",num1 )

 

Output

type of age is <class 'str'>
type of age is <class 'int'> and value is 2

 

Explanation

  • we take same example, but here we convert string to integer with base value 2.
  • base 2 will take String value in form of 01 (binary format) and convert to like 20 + 21+ 22.. etc. for 1,  hence 10 value will be 0 + 21 = 0+2 =2

Note: base 2 will convert the binary value to  20 + 21+ 22.. etc.  It will put 2 power  where 1 is value and 0 where 0 is value.