How To Convert Python String To Int


  • In Python programming, function int() is a standard inbuilt function that converts the string into integer value and function str() is an inbuilt function that converts int to string.
  • Python also defines the type conversion functions to convert directly from one data type to another data type, which is very useful in competitive programming.

 


How to Convert Strings into Integers in Python

Example:-

# Here my_age is a string object
my_age = "27"
print(my_age)
# below Converting string to integer
int_age = int(my_age)
print(int_age)

Output

27
27

In above example we can see the output is visually similar but we have to keep in mind that the first line prints a string object while the line next prints a integer object which is further illustrated in the next example:-

# Here my_age is a string object
my_age = "27"
print(my_age+3)

Output

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(my_age+3)
TypeError: cannot concatenate 'str' and 'int' objects

 


The above error make it clear that we have to convert the my_age object to an integer before adding something to it.

my_age = "27"
int_age = int(my_age)
print(int_age+3)

Output

30

 

 

 


 

Leave a Reply

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