Pythonic way to determine if a string is a number
nick at craig-wood.com
Mon Feb 16 22:31:55 CET 2009
python at bdurham.com <python at bdurham.com> wrote:
> Thanks for everyone's feedback. I believe my original post's code
> (updated following my signature) was in line with this list's feedback.
> Christian: Thanks for reminding me about exponential formats. My updated
> code accounts for these type of numbers. I don't need to handle inf or
> nan values. My original code's except catches an explicit ValueError
> exception per your concern about bare excepts.
> # str_to_num.py
> def isnumber( input ):
> num = float( input )
> return True
> except ValueError:
> return False
That is a fine solution.
Last time I had to solve this I had a specific format of number to
parse - I didn't want to include all the python formats. This is what
I came up with... This particular code returns the converted number
or 0.0 - adjust as you see fit!
_float_pattern = re.compile(r"^\s*([-+]?(\d*\.)?\d+([eE][-+]?\d+)?)")
Convert a string to an float in the same way the c-library atof()
does. Ie only converting as much as it can and returning 0.0 for
match = _float_pattern.search(value)
>>> atof("15.5 Sausages")
>>> atof(" 17.2")
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list