Convert String to Int in Python
In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conversion.
Using int() Function
The simplest way to convert a string to an integer in Python is by using the int() function. This function attempts to parse the entire string as a base-10 integer.
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.
Table of Content
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().
# 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
Using 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.
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.
Using 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.
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.