【问题标题】:How to validate floating numbers in isdigit() in python如何在python中验证isdigit()中的浮点数
【发布时间】:2020-08-16 12:22:15
【问题描述】:

我正在尝试验证用户输入,并且用户输入必须是正整数,包括浮点数。我尝试使用 isdigit(),它也验证了所有非数字输入和负整数,但无法验证浮点数。 下面是我的代码

 def is_number(s):
     while (s.isdigit() == False):
       s = input("Enter only numbers, not less than 0 : ")
 return float(s)

#方法调用

 while('true'):
      membershipFee = is_number(input('Enter the base membership fee, or zero to quit: '))
              

【问题讨论】:

  • 如果浮点数返回floatint。如果int 应该总是向下取整吗?
  • 哦,谢谢指出,那应该是浮动..cheers

标签: python


【解决方案1】:

您可以尝试转换并捕获任何错误。如果python快乐,你就快乐。

def is_number(s):
    while True:
        try:
            retval = float(s)
            if s >= 0.:
                return s
        except ValueError:
            pass
        s = input("Enter only numbers, not less than 0 : ")

【讨论】:

    【解决方案2】:

    如果你想使用 isdigit(),你不能在浮点数上使用它。一种可能的解决方案是使用正则表达式来验证您的浮点数。

    Using isdigit for floats?

    【讨论】:

      【解决方案3】:

      你可以尝试做这样的事情:

      #check if there is only one decimal place and check if it is not negative
      s = input('Enter the number :')
      if s.replace('.','',1).isdigit() and '-' not in s:
          print ('OK to process')
      else:
          print ('not OK to process')
      

      这将确保您获得所需的数字。

      【讨论】:

        【解决方案4】:

        你应该试试这个

        def isNumber(f):
            return all([p.isdigit() for p in [f[:f.find('.')], f[f.find('.')+1:]] if len(p)])
        
        print(isNumber('12.543'))
        print(isNumber('185'))
        print(isNumber('.2341'))
        print(isNumber('163.'))
        print(isNumber('14.356.67'))
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-12-19
          • 2015-07-14
          • 2011-05-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多