Friday, September 2, 2022

Convert String to int in Python

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

  1. Convert String to float in Python
  2. Python Program to Display Fibonacci Series
  3. Python String isdigit() Method
  4. Operator Overloading in Python
  5. Removing Spaces From String in Python

You may also like-

  1. Comparing Two Strings in Python
  2. Python Functions : Returning Multiple Values
  3. Python Exception Handling Tutorial
  4. Local, Nonlocal And Global Variables in Python
  5. Converting String to int in Java
  6. ArrayList in Java With Examples
  7. Lambda Expressions in Java 8
  8. Interface Default Methods in Java 8