Pythonic way to determine if a string is a number

Nick Craig-Wood nick at craig-wood.com
Mon Feb 16 16:31:55 EST 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.
> 
>  Malcolm
> 
> <code>
>  # str_to_num.py
> 
>  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 = _float_pattern.search(value)
    if match:
        return float(match.group(1))
    return 0.0

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

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list