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

Hey guys, in this blog we will see a Python Program to Check If a String Is a Number (Float).

Using float()

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

print(isfloat('12.s'))
print(isfloat('2.20'))

Output

False
True
  • For checking if a string is float or not we have defined function isfloat().
  • This function simply comprises a try/except.
  • In try part we will simply try to convert our num to float and if this operation is successful, we will return True. This means that this string can be interpreted as a float.
  • If any error occurs, our except part will get active and return False.

Check out our other python programming examples

Abhishek Sharma
Abhishek Sharma

Started my Data Science journey in my 2nd year of college and since then continuously into it because of the magical powers of ML and continuously doing projects in almost every domain of AI like ML, DL, CV, NLP.

Articles: 520

Subscribe to our Newsletter

Subscribe to our newsletter and receive all latest projects...

Leave a Reply

Your email address will not be published. Required fields are marked *