python - 如何检查输入是否为小数?

标签 python input

我希望一个输入一直要求输入,除非输入是一个不超过两位小数的数字。

number = input('please enter a number')  
while number **is not a decimal (insert code)**:  
. . . .number = input('incorrect input,\nplease enter a number')

最佳答案

您可以使用评论中提到的正则表达式:

import re

def hasAtMostTwoDecimalDigits(x):
    return re.match("^\d*.\d{0,2}$", x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

或者使用decimal模块:

from decimal import Decimal

def hasAtMostTwoDecimalDigits(x):
    x = Decimal(x)
    return int(1000*x)==10*int(100*x)

number = input("please enter a number")
while not hasAtMostTwoDecimalDigits(number):
    number = input("incorrect input,\nplease enter a number")

Jon Clements 所述在评论中,这可以变得更简单:

def hasAtMostTwoDecimalDigits(x):
    return Decimal(x).as_tuple().exponent >= -2

关于python - 如何检查输入是否为小数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21080555/

相关文章:

c - fscanf 计数 "invisible"个空格

php - Laravel 表单输入 - 如何设置最大长度

python - numpy argsort 性能缓慢

jquery - 如何获取表单中所有输入的值

python - Windows中是否有等效的evdev

javascript - 读取变量中上传的文本文件内容

python - 使用 Python 在 Mac OSX 中转义正斜杠路径目录?

python - 最后获得带有附加项的成对迭代器

python - 导入错误 : cannot import name 'AutoModelWithLMHead' from 'transformers'

python - 从维基百科文章中提取统计信息