Last Updated : 27 Oct, 2024
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() FunctionThe 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.
Python
s = "42"
num = int(s)
print(num)
Explanation: The int() function takes the string s and converts it into an integer.
Note:
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)
Explanation:
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")
Invalid input: cannot convert to integer
Explanation:
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.")
Explanation: s.isdigit() returns True if s contains only digits, this allow us safe conversion to an integer.
Python Program to Convert String to an Integer
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4