Check if a given string is numeric in Python
This post will discuss how to check if a string is numeric in Python.
1. Using float() function
The idea is to convert the string to a float and return false if the conversion is not possible. This can be easily done using the float(x) function, which converts the string x into a floating-point number and raises the ValueError when it cannot convert x into a valid float.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
def isNumeric(s): try: float(s) return True except ValueError: return False if __name__ == '__main__': s = "100" print(isNumeric(s)) # True |
Note that the float(x) function accepts a NaN (not-a-number) or a positive or negative infinity as the string argument.
2. Using complex() function
Alternatively, you can use the complex() function to convert a string to a complex number. Like the float() function, it accepts a NaN (not-a-number) or a positive or negative infinity as the string argument and returns True.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
def isNumeric(s): try: complex(s) return True except ValueError: return False if __name__ == '__main__': s = "100" print(isNumeric(s)) # True |
3. Using isdigit() function
Another option is to use the str.isdigit() function, which returns True when the given string is a positive integer. However, it returns False when the string is a float number or a negative number.
|
1 2 3 4 5 6 7 8 |
def isNumeric(s): return s.isdigit() if __name__ == '__main__': s = "100" print(isNumeric(s)) # True |
That’s all about determining whether a given string is numeric in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)