isFloat: Without Exception-Handling

Magnus Lyckå magnus at thinkware.se
Fri Sep 20 09:34:29 EDT 2002


Thomas Guettler wrote:
> Is there a way to write the following
> method without using exceptions?
> 
> def isFloat(string):
>     is_float=1
>     try:
>         float(string)
>     except:
>         is_float=0
>     return is_float

Something like this perhaps:

import re

def isFloat(S):
     floatRE = r"^[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?$"
     return re.match(floatRE, str(S)) is not None

I'm not sure it's faster though.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se




More information about the Python-list mailing list