How can I verify if a string is a valid float? [duplicate]

耗尽温柔 提交于 2020-01-04 02:54:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!