使用 isdigit 表示浮点数?
a = raw_input('How much is 1 share in that company? ')
while not a.isdigit():
print("You need to write a number!\n")
a = raw_input('How much is 1 share in that company? ')
仅当用户输入整数
时才有效,但我希望即使他们输入浮点
也能工作,但当他们输入字符串
时则不起作用>。
因此,用户应该能够输入 9
和 9.2
,但不能输入 abc
。
我该怎么做呢?
a = raw_input('How much is 1 share in that company? ')
while not a.isdigit():
print("You need to write a number!\n")
a = raw_input('How much is 1 share in that company? ')
This only works if the user enters an integer
, but I want it to work even if they enter a float
, but not when they enter a string
.
So the user should be able to enter both 9
and 9.2
, but not abc
.
How should I do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
EAFP
EAFP
现有的答案是正确的,因为更 Pythonic 的方式通常是
try... except
(即 EAFP,“请求宽恕比请求许可更容易”)。但是,如果您确实想要进行验证,则可以在使用
isdigit()
之前精确删除 1 位小数点。请注意,这并没有将浮点数视为与整数有任何不同。如果您确实需要的话,您可以添加该检查。
The existing answers are correct in that the more Pythonic way is usually to
try...except
(i.e. EAFP, "easier to ask for forgiveness than permission").However, if you really want to do the validation, you could remove exactly 1 decimal point before using
isdigit()
.Notice that this does not treat floats any different from ints however. You could add that check if you really need it though.
使用正则表达式。
Use regular expressions.
基于 dan04 的答案:
用法:
Building on dan04's answer:
usage:
请注意,这也适用于负浮点数。
Note that this will work for negative
float
s as well.我认为@dan04有正确的方法(EAFP),但不幸的是现实世界通常是一个特殊情况,并且确实需要一些额外的代码来管理事物 - 所以下面是一个更详细的,但也更务实(和现实) :
使用示例:
I think @dan04 has the right approach (EAFP), but unfortunately the real world is often a special case and some additional code is really required to manage things—so below is a more elaborate, but also a bit more pragmatic (and realistic):
Sample usage:
如果字符串包含一些特殊字符,例如下划线(例如“1_1”),则提供的答案将失败。在我测试的所有情况下,以下函数都会返回正确的答案。
The provided answers fail if the string contains some special characters such as underscore (e.g. '1_1'). The following function returns correct answer in all case that I tested.