![]() |
VOOZH | about |
Data entered by users or read from external sources is often stored as strings. To perform mathematical operations on these values, they must first be converted into integers. Python provides efficient ways to convert strings to integers while also handling special cases such as different number bases and invalid inputs.
Example:
Input: age = "25"
Output: 25
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.
42 <class 'int'>
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.
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().
10 10
Explanation:
If the input string contains non-numeric characters, int() will raise a ValueError. To handle this gracefully, we use a try-except block.
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.
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.