We can convert a string to Int in Python using a built-in function int(). This function takes a string as an argument and returns an integer. Let’s start coding
Code:
str = '123'
intg = int(str)
print("Value in str:", str)
print("Orignal Type:", type(str))
print("Converted Type:", type(intg))
Output:
Value in str: 123
Orignal Type: <class 'str'>
Converted Type: <class 'int'>
Error:
If the string cannot be converted to an integer, this function will return an error.
Code:
str = 'This is a string'
intg = int(str)
print("Value in str:", str)
print("Orignal Type:", type(str))
print("Converted Type:", type(intg))
Output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
d:\Study\Blog_Codes\string.ipynb Cell 6 in <cell line: 4>()
1 #2 how to convert string to int in python
3 str = 'This is a string'
----> 4 intg = int(str)
5 print("Value in str:", str)
6 print("Orignal Type:", type(str))
ValueError: invalid literal for int() with base 10: 'This is a string'
References: