checking if a string contains a number

Tim Williams (gmail) tdwdotnet at gmail.com
Tue Dec 20 15:01:06 CET 2005


On 20/12/05, Suresh Jeevanandam <jm.suresh at gmail.com> wrote:
>
> Hi,
>         I have a string like,
>         s1 = '12e3'
>         s2 = 'junk'
>
>         Now before converting these values to float, I want to check if
> they
> are valid numbers.
>
>         s1.isdigit returns False.
>
>         Is there any other function which would return True for s1 and
> False
> for s2.


float()  itself can do the checking for you.

>>> for n in ['12e3','junk']:
...     try:
...         float(n)
...     except:
...         print "not valid: ",  n
...
12000.0
not valid: junk
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20051220/5e05c3b4/attachment.html>


More information about the Python-list mailing list