3

What I want to do is to verify if a string is numeric -- a float -- but I haven't found a string property to do this. Maybe there isn't one. I have a problem with this code:

N = raw_input("Ingresa Nanometros:");
if ((N != "") and (N.isdigit() or N.isdecimal())):
    N = float(N);
    print "%f" % N;

As you can see, what I need is to take only the numbers, either decimal or float. N.isdecimal() does not resolve the problem that I have in mind.

4

1 に答える 1

10
try:
    N = float(N)
except ValueError:
    pass
except TypeError:
    pass

This tries to convert N to a float. However, if it isn't possible (because it isn't a number), it will pass (do nothing).

I suggest you read about try and except blocks.

You could also do:

try:
    N = float(N)
except (ValueError, TypeError):
    pass
于 2013-02-19T02:08:59.347 に答える