如何检查raw_input是否为浮点数并且只能有一个小数点?
代码:
x=raw_input("Enter: ")
if x.isfloat():
print x
else:
print "error"
错误:
Traceback (most recent call last):
File "C:/Python27/DLLs/delete", line 4, in <module>
if not x.isNumber():
AttributeError: 'str' object has no attribute 'isNumber'
1 个回答
4
为什么不直接用 try
来试试呢?
x = raw_input("Enter: ")
try:
x = float(x)
except ValueError:
print "error"
else:
print x
这种叫做 “事后求饶比事先请求许可更简单” 的风格在Python中很常见。
如果你确实是想检查小数点后只有一位数字的情况,可以稍微调整一下:
try:
if len(x.split(".", 1)[1]) == 1:
x = float(x)
else:
print "error" # too many d.p.
except (IndexError, ValueError):
print "error" # no '.' or not a float
else:
print x
在这里,IndexError
会捕捉到 x
中没有任何 '.'
的情况,而 ValueError
则会捕捉到 x
不能被理解为一个 float
的情况。一般来说,你可能想把这些检查分开,这样可以给用户报告一个更有用的错误信息(例如 "错误:无法将 '{0}' 转换为 float.".format(x)
),或者甚至抛出一个真正的 Exception
。