【问题标题】:String index out of range when referring to different if statements引用不同的 if 语句时字符串索引超出范围
【发布时间】:2019-08-31 02:34:09
【问题描述】:

我正在为类制作一个计算器程序,当我提到减号、乘号和除号时出现字符串索引超出范围错误,但在我的系列中首先提到加法时没有得到加号if/elif 语句。

problem = ("123 * 456")
numLength = 0
placeCount = -1
for i in problem:
    placeCount = placeCount + 1
    if i == "0" or i == "1" or i == "2" or i == "3" or i == "4" or i == "5" or i == "6" or i == "7" or i == "8" or i == "9":
        numLength = numLength + 1
        holdingList.append(i)
    if i == " " or i == ")" and numLength > 0:
        theNum = concatenate_list_data(holdingList)
        if problem[placeCount - (numLength + 2)] == "+" or problem[placeCount + 1] == "+":
            theNum = int(theNum)
            adding.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "-" or problem[placeCount + 1] == "-":
            theNum = int(theNum)
            subtracting.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "*" or problem[placeCount + 1] == "*":
            theNum = int(theNum)
            multing.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""
        elif problem[placeCount - (numLength + 2)] == "/" or problem[placeCount + 1] == "/":
            theNum = int(theNum)
            dividing.append(theNum)
            holdingList = []
            numLength = 0
            theNum = ""

错误:

Traceback (most recent call last):
    File "/Users/nick/Desktop/Programs/calculator.py", line 61, in <module>
      if problem[placeCount - (numLength + 2)] == "+" or problem[placeCount + 1] == "+":
    IndexError: string index out of range

【问题讨论】:

  • 嗨,你能发布堆栈跟踪吗?
  • Traceback(最近一次调用最后一次):文件“/Users/nick/Desktop/Programs/calculator.py”,第 61 行,在 中如果有问题[placeCount - (numLength + 2)] == "+" 或问题[placeCount + 1] == "+": IndexError: string index out of range
  • 变量problem的值是多少
  • 您输入的测试字符串有多长?如果第一次迭代中 placeCount 为 0,则从中减去 3 并索引问题,字符 problem[-3] 是什么?
  • problem 适合哪里?

标签: python string indexing


【解决方案1】:

如果输入是:

problem = '(123 * 456)'

当您到达字符串末尾的) 时,problem[placeCount + 1] 在字符串之外。

当运算符为+ 时,您不会收到错误消息,因为逻辑运算符会进行快捷操作。由于problem[placeCount - (numLength + 2)] == "+" 为真,它从不尝试评估problem[placeCount + 1] == "+"

但是当problem[placeCount - (numLength + 2)] == "+" 为假时,它会尝试测试problem[placeCount + 1]。这在字符串之外访问并得到一个错误。

将测试改为:

if problem[placeCount - (numLength + 2)] == "+" or (placeCount < len(problem) - 1 and problem[placeCount + 1] == "+"):

对于所有其他运算符也是如此。

【讨论】:

  • 谢谢!我自己不会想到这一点
猜你喜欢
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-19
相关资源
最近更新 更多