Checking if a string can be converted to float in Python Checking if a string can be converted to float in Python python python

Checking if a string can be converted to float in Python


I would just use..

try:    float(element)except ValueError:    print "Not a float"

..it's simple, and it works. Note that it will still throw OverflowError if element is e.g. 1<<1024.

Another option would be a regular expression:

import reif re.match(r'^-?\d+(?:\.\d+)$', element) is None:    print "Not float"


Python method to check for float:

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

UNIT TESTING!

What is, and is not a float may surprise you:

Command to parse                        Is it a float?  Comment--------------------------------------  --------------- ------------print(isfloat(""))                      Falseprint(isfloat("1234567"))               True print(isfloat("NaN"))                   True            nan is also floatprint(isfloat("NaNananana BATMAN"))     Falseprint(isfloat("123.456"))               Trueprint(isfloat("123.E4"))                Trueprint(isfloat(".1"))                    Trueprint(isfloat("1,234"))                 Falseprint(isfloat("NULL"))                  False           case insensitiveprint(isfloat(",1"))                    False           print(isfloat("123.EE4"))               False           print(isfloat("6.523537535629999e-07")) Trueprint(isfloat("6e777777"))              True            This is same as Infprint(isfloat("-iNF"))                  Trueprint(isfloat("1.797693e+308"))         Trueprint(isfloat("infinity"))              Trueprint(isfloat("infinity and BEYOND"))   Falseprint(isfloat("12.34.56"))              False           Two dots not allowed.print(isfloat("#56"))                   Falseprint(isfloat("56%"))                   Falseprint(isfloat("0E0"))                   Trueprint(isfloat("x86E0"))                 Falseprint(isfloat("86-5"))                  Falseprint(isfloat("True"))                  False           Boolean is not a float.   print(isfloat(True))                    True            Boolean is a floatprint(isfloat("+1e1^5"))                Falseprint(isfloat("+1e1"))                  Trueprint(isfloat("+1e1.3"))                Falseprint(isfloat("+1.3P1"))                Falseprint(isfloat("-+1"))                   Falseprint(isfloat("(1)"))                   False           brackets not interpreted


'1.43'.replace('.','',1).isdigit()

which will return true only if there is one or no '.' in the string of digits.

'1.4.3'.replace('.','',1).isdigit()

will return false

'1.ww'.replace('.','',1).isdigit()

will return false