首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否对浮点数使用isdigit?

是否对浮点数使用isdigit?
EN

Stack Overflow用户
提问于 2010-11-10 04:23:30
回答 8查看 54.6K关注 0票数 36
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? ')

这只在用户输入integer时起作用,但我希望即使他们输入float也能起作用,但当他们输入string时就不起作用。

因此,用户应该能够输入99.2,但不能输入abc

我怎么发动汽车呢?

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2010-11-10 04:33:25

使用正则表达式。

import re

p = re.compile('\d+(\.\d+)?')

a = raw_input('How much is 1 share in that company? ')

while p.match(a) == None:
    print "You need to write a number!\n"
    a = raw_input('How much is 1 share in that company? ')
票数 15
EN

Stack Overflow用户

发布于 2010-11-10 04:25:57

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")
票数 40
EN

Stack Overflow用户

发布于 2011-10-04 13:38:16

现有的答案是正确的,因为更多的Pythonic方法通常是try...except (即EAFP)。

但是,如果您真的想进行验证,则可以在使用isdigit()之前删除1个小数点。

>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False

请注意,这并没有将浮点型与整型区别对待。如果你真的需要的话,你可以添加这个检查。

票数 28
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4138202

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档