In this post we’ll see how to convert String to int in Python.
If you have an integer represented as String literal then you need to convert it to integer value if you have to use it in any arithmetic operation.
For example-
num1 = "50" num2 = 20 result = num1 + num2 print("Sum is-", result)
Output
Traceback (most recent call last): File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in <module> result = num1 + num2 TypeError: can only concatenate str (not "int") to str
As you can see since the first operand is string so Python tries to concatenate the second operand to the first rather than adding them. In such scenario you need to convert string to int.
Python program - convert String to int
To convert a Python String to an int pass that String to int() function which returns an integer object constructed from the passed string.
num1 = "50" num2 = 20 # converting num1 to int result = int(num1) + num2 print("Sum is-", result)
Output
Sum is- 70
ValueError while conversion
If the string doesn’t represent a valid number that can be converted to int, ValueError is raised. While doing such conversions it is better to use try and except for exception handling.
def add(): try: num1 = "abc" num2 = 20 # converting num1 to int result = int(num1) + num2 print("Sum is-", result) except ValueError as error: print('Error while conversion:', error) add()
Output
Error while conversion: invalid literal for int() with base 10: 'abc'
Converting String with commas to int
If String variable is storing a number with commas (as example str_num="6,00,000") then one of the option is to use replace()
method of the str class to remove
commas before converting string to int.
def add(): try: num1 = "6,45,234" num2 = 230000 # converting num1 to int result = int(num1.replace(',', '')) + num2 print("Sum is-", result) except ValueError as error: print('Error while conversion:', error) add()
Output
Sum is- 875234
That's all for this topic Convert String to int in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Programs Page
Related Topics
You may also like-