Chris Upchurch Chris Upchurch - 1 year ago 60
Python Question

Checking if a string can be converted to float in Python

I've got some Python code that runs through a list of strings and converts them to integers or floating point numbers if possible. Doing this for integers is pretty easy

if element.isdigit():

Floating point numbers are more difficult. Right now I'm using partition('.') to split the string and checking to make sure that one or both sides are digits.

if (partition[0].isdigit() and partition[1]=='.' and partition[2].isdigit()) or (partition[0]=='' and partition[1]=='.' and partition[2].isdigit()) or (partition[0].isdigit() and partition[1]=='.' and partition[2]==''):

This works, but obviously the if statement for that is a bit of a bear. The other solution I considered is to just wrap the conversion in a try/catch block and see if it succeeds, as described in this question.

Anyone have any other ideas? Opinions on the relative merits of the partition and try/catch approaches?

dbr dbr
Answer Source

I would just use..

except ValueError:
    print "Not a float"'s simple, and it works

Another option would be a regular expression:

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