Convert String to Int in Python

Last Updated : 23 May, 2026

Convert String to Int means changing a value written as text (string) into a number (integer) so you can do math with it.

int() Function

The simplest way to convert a string to an integer in Python is by using the int() function. This function converts the entire string into a base-10 integer.

Python
s = "42"
num = int(s)
print(num)

Output
42

Explanation: The int() function takes the string s and converts it into an integer.

Note:

  • If the string contains non-numeric characters or is empty, int() will raise a ValueError.
  • int() function automatically handles leading and trailing whitespaces, so int() function trims whitespaces and converts the core numeric part to an integer.

Converting Strings with Different Bases

The int() function also supports other number bases, such as binary (base-2) or hexadecimal (base-16). To specify the base during conversion, we have to provide the base in the second argument of int().

Python
# Binary string
s = "1010"
num = int(s, 2)
print(num)

# Hexadecimal string
s = "A"
num = int(s, 16)
print(num)

Output
10
10

Explanation:

  • Here, int(s, 2) interprets s as a binary string, returning 10 in decimal.
  • Similarly, int(s, 16) treats s as a hexadecimal string.

Handling Invalid Input String

try and except

If the input string contains non-numeric characters, int() will raise a ValueError. To handle this gracefully, we use a try-except block.

Python
s = "abc"
try:
    num = int(s)
    print(num)
except ValueError:
    print("Invalid input: cannot convert to integer")

Output
Invalid input: cannot convert to integer

Explanation:

  • try attempts to convert the string s to an integer.
  • If s contains non-numeric characters, a ValueError is raised and we print an error message instead.

str.isdigit()

Use str.isdigit() to check if a string is entirely numeric before converting. This method make sure that the input only contains digits.

Python
s = "12345"
if s.isdigit():
    num = int(s)
    print(num)
else:
    print("The string is not numeric.")

Output
12345

Explanation: s.isdigit() returns True if s contains only digits, this allow us safe conversion to an integer.

Note: isdigit() returns False for negative numbers (such as "-12") and decimal values (such as "3.14"), so it is suitable only for strings containing digits only.

Comment