【问题标题】:How to check if a raw input is an integer or float (including negatives) without using try-except如何在不使用 try-except 的情况下检查原始输入是整数还是浮点数(包括负数)
【发布时间】:2019-08-18 10:11:56
【问题描述】:

作为更大的 Python 作业问题的一部分,我正在尝试检查字符串输入是否包含正/负整数或浮点数,如果包含则返回 True,否则返回 False。

作业问题将假设用户输入一个非常简单的数学表达式,用空格分隔(例如 8 / ( 2 + 2 )),之后,表达式将被分解为列表中的单独字符(例如["8"、"/"、"("、"2"、"+"、"2"、")"])。然后,我将通过一个“for”循环运行此列表,该循环根据当前令牌的类型增加计数器变量的数量(例如,如果 currentToken 为“2”,则operandCount += 1)。

到目前为止,我很难使用包含正/负浮点数或 int 类型数字(例如“8”、“-9”、“4.6”)的 currentToken 来完成此操作。这里的主要挑战是我的教授不允许我们在代码中的任何地方使用 try-except,因此排除了我在网上找到的许多解决方案,因为其中许多都涉及捕获错误消息。

我最接近解决这个问题的方法是使用“isnumeric()”和“isdigit()”方法。

# Assume that the user will enter in a simple math expression, separated by whitespace.
expression = input("Enter an expression: ")
expr = expression.split()

operandCount = 0

for currentToken in expr:
    if currentToken.isnumeric() == True:
        operandCount += 1

        # operandCount should increase when the 'for' loop encounters
        # a positive/negative integer/float.

但是,它只对包含纯正整数的字符串返回 True。我需要它能够为正数和负数的整数和浮点数返回 True。提前感谢您的任何建议!

【问题讨论】:

  • 您可以使用正则表达式(尽管在这种情况下它们不像 Python 那样)。在这里您可以找到更多选项:stackoverflow.com/questions/354038/… 在 user2489252 的回答中。
  • 括号算什么?
  • 我认为你现在在做什么是错误的,当它是真的时你增加operandCount。难道你不想在它为假时增加operandCount,例如当你有一个“/”而不是一个数字时?

标签: python python-3.x


【解决方案1】:

应用正则表达式来搜索可选的数字字符串

  • 负数:-1
  • 有逗号分隔:120,000
  • 有一个可选的小数点:0.34, .1415926
import re 
for currentToken in expr:   
   m = re.match("^[-\.\d]+[,]?[\d]*[\.]?[\d]?$", str(currentToken)) 
  if (m): 
     print "number:", m.group[0]

【讨论】:

    【解决方案2】:

    正如skymon 指出的那样,使用regex 是个好主意,这里有一个例子:

    import re
    
    def isAdigit(text, pat=r'^-*\d+\.*\d*[ \t]*$'):
        if re.search(pat, text) != None:
            return True
    
        return False
    
    expression = input("Enter an expression: ")
    expr = expression.split()
    
    operandCount = 0
    
    for currentToken in expr:
        if isAdigit(currentToken):
            operandCount += 1
    
    print (operandCount)
    

    示例用法:

    输入:1 + 2 / ( 69 * -420 ) - -3.14 => 输出:5

    我还建议您了解有关regex 的更多信息。

    【讨论】:

      猜你喜欢
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 2011-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多