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, includingerror handlingand 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.
Pythons="42"num=int(s)print(num)
Explanation: The int() function takes the strings and converts it into an integer.
Note:
- If the string contains non-numeric characters or is empty,int() will raise aValueError.
- int()function automatically handlesleading andtrailingwhitespaces, so int() function trims whitespaces and converts the core numeric part to an integer.
Converting Strings with Different Bases
Theint() 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 strings="1010"num=int(s,2)print(num)# Hexadecimal strings="A"num=int(s,16)print(num)
Explanation:
- Here, int(s, 2) interpretssas a binary string, returning10 in decimal.
- Similarly,int(s, 16) treatss as a hexadecimal string.
Handling Invalid Input String
Using try and except
If the input string contains non-numeric characters,int()will raise aValueError. To handle this gracefully, we use atry-exceptblock.
Pythons="abc"try:num=int(s)print(num)exceptValueError:print("Invalid input: cannot convert to integer")
OutputInvalid input: cannot convert to integer
Explanation:
- try attempts to convert the strings to an integer.
- Ifs contains non-numeric characters, aValueError is raised and we print an error message instead.
Using str.isdigit()
Usestr.isdigit()to check if a string is entirely numeric before converting. This method make sure that the input only contains digits.
Pythons="12345"ifs.isdigit():num=int(s)print(num)else:print("The string is not numeric.")
Explanation: s.isdigit()returnsTrue ifscontains only digits, this allow us safe conversion to an integer.
Python Program to Convert String to an Integer