How can I check if a string is a valid float value?
What I want to do is check if the string is numeric - float, but I didn't find a string property for that. Perhaps they are not. 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, I only need to accept numbers, decimal or floats. N.isdecimal()
does not solve the problem I remember about.
+3
source to share
1 answer
try:
N = float(N)
except ValueError:
pass
except TypeError:
pass
It is trying to convert N
to float
. However, if this is not possible (because it is not a number), it will pass
(do nothing).
I invite you to read and blocks . try
except
You can also do:
try:
N = float(N)
except (ValueError, TypeError):
pass
+10
source to share