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

Leave a Reply

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