Pythonic way to determine if a string is a number

Nick Craig-Wood nick at
Mon Feb 16 22:31:55 CET 2009

python at <python at> 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.
>  Malcolm
> <code>
>  #
>  def isnumber( input ):
>      try:
>          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!

import re

_float_pattern   = re.compile(r"^\s*([-+]?(\d*\.)?\d+([eE][-+]?\d+)?)")

def atof(value):
    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
    an error.
    match =
    if match:
        return float(
    return 0.0

>>> atof("15.5 Sausages")
>>> atof("   17.2")
>>> atof("0x12")
>>> atof("8.3.2")
>>> atof("potato")

Nick Craig-Wood <nick at> --

More information about the Python-list mailing list