Python Program to Check If a String Is a Number (Float)

To understand this example, you should have the knowledge of the following Python programming topics:


Using float()

def isfloat(num):
    try:
        float(num)
        return True
    except ValueError:
        return False

print(isfloat('s12'))
print(isfloat('1.123'))

Output

False
True

Here, we have used try except in order to handle the ValueError if the string is not a float.

  • In the function isfloat(), float() tries to convert num to float. If it is successful, then the function returns True.
  • Else, ValueError is raised and returns False.

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.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community