问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/14948651/how-can-i-verify-if-a-string-is-a-valid-float