In this example, you will learn to check if a string is a number (float).
def isfloat(num): try: float(num) return True except ValueError: return False print(isfloat('s12')) print(isfloat('1.123'))
Here, we have used try except in order to handle the ValueError if the string is not a float.
In the function
tries to convert num to float. If it is successful, then the function returns
is raised and returns
For example, ‘s12’ is alphanumeric, so it cannot be converted to float and False is returned; whereas, ‘1.123’ is a numeric, so it is successfully converted to float.