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.

Download  Run Code

 
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.

Download  Run Code

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.

Download  Run Code

That’s all about determining whether a given string is numeric in Python.