如何验证字符串是否为有效浮点数? [英] How can I verify if a string is a valid float?
本文介绍了如何验证字符串是否为有效浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要做的是验证一个字符串是否是数字——一个浮点数——但我还没有找到一个字符串属性来做到这一点.可能一个都没有.这段代码有问题:
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;
如您所见,我只需要取数字,无论是十进制数还是浮点数.N.isdecimal()
没有解决我想到的问题.
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.
推荐答案
try:
N = float(N)
except ValueError:
pass
except TypeError:
pass
这会尝试将 N
转换为 float
.但是,如果不可能(因为它不是数字),它将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).
我建议你阅读 try
和except
块.
I suggest you read about try
and except
blocks.
你也可以这样做:
try:
N = float(N)
except (ValueError, TypeError):
pass
这篇关于如何验证字符串是否为有效浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文