checking if a string contains a number

S

Suresh Jeevanandam

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.

Thanks
 
L

Larry Bates

You should probably work through the tutorials.

Use a try block:

try: x=float(s)
except ValueError:
print 'Non-numeric value %s found' % s

-Larry Bates
 
S

Steven D'Aprano

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.
 
S

Steven D'Aprano

isinstance(12e3, (int, float))

That won't work, because s1 is a *string*, not a float. The original
poster is asking how to check whether the string can be converted to a
float successfully before actually trying to convert it to a float.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top