checking if a string contains a number

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Dec 20 22:37:41 CET 2005


On Tue, 20 Dec 2005 19:16:46 +0530, Suresh Jeevanandam 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.

Just try converting them:

float_list = []
for s in string_list:
    try:
        float_list.append(float(s))
    except ValueError:
        # ignore bad strings
        pass
do_something_with_floats(float_list)


> 	s1.isdigit returns False.

"2" is a digit. "23" is two digits. You want something like s1.isfloat(),
but why bother checking first? Just Do It.

> 	Is there any other function which would return True for s1 and False
> for s2.

>From an interactive interpreter, call dir(s1). That will give you a list
of string methods. Then call help(s1.method) to learn what that method
does.


-- 
Steven.




More information about the Python-list mailing list