Checking if a string can be converted to float in Python

Chris Upchurch picture Chris Upchurch · Apr 9, 2009 · Viewed 299.4k times · Source

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():
  newelement = int(element)

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.

partition = element.partition('.')
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] == ''):
  newelement = float(element)

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?

Answer

dbr picture dbr · Apr 9, 2009

I would just use..

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

..it's simple, and it works

Another option would be a regular expression:

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