How to check if a string is numeric in Python
How to check if a string is numeric in Python.
Here's a step-by-step tutorial on how to check if a string is numeric in Python:
Start by defining a function called
is_numericthat takes a string as input. This function will check if the string is numeric and return a boolean value (True or False) accordingly.Inside the
is_numericfunction, use thetryandexceptstatements to handle any potential errors that may occur when trying to convert the string to a numeric type.Inside the
tryblock, use thefloatorintbuilt-in functions to attempt to convert the string to a float or integer respectively. If the conversion is successful, it means the string is numeric, so return True.If an exception occurs during the conversion (e.g., a
ValueError), it means the string is not numeric, so catch the exception using theexceptblock and return False.
Here's an example implementation of the is_numeric function:
def is_numeric(string):
try:
float(string)
return True
except ValueError:
return False
You can use this function to check if a string is numeric by calling it and passing the string as an argument. For example:
print(is_numeric("123")) # Output: True
print(is_numeric("-45.67")) # Output: True
print(is_numeric("3.14abc")) # Output: False
print(is_numeric("xyz")) # Output: False
In the first two examples, the strings are numeric and the function returns True. In the last two examples, the strings are not numeric and the function returns False.
This implementation works for both integers and floating-point numbers. If you only want to check for integers, you can modify the function to use the int function instead of float.