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 re
if re.match(r'^-?\d+(?:\.\d+)$', element) is None:
    print "Not float"

Leave a Comment