不满足1个特定条件时出现“ IndexError:列表索引超出范围”

时间:2019-07-13 20:19:02

标签: python list function

该代码仍会找到正确的电话号码,但会给出与xxx-xxx-xxxx格式不匹配的电话号码错误。

为什么每个循环都不会发生错误,而是只显示xxxx-xxx-xxx格式的数字

我尝试使用'except'函数和python visualiser。如果我仅保留1个if语句以检查数字的长度,则代码可以正常工作[0]

谢谢大家!

代码:

def numCheck(digits):
    digits = digits.split('-')
    if len(digits[0]) != 3:
        return False
    if len(digits[1]) != 3:
        return False
    if len(digits[2]) != 4:
        return False
    joinDigits = ''.join(digits)
    if not joinDigits.isdecimal():
        return False
    if len(joinDigits) != 10:
        return False
    else:
        return True

phoneNo = ('nec dictum tellus. Fusce vitae 2222-345-678 risus ac. Aenean condimentum 124-567-6893 e. Pelunt erat fermentum. Nulla vel fes 234-574-1111 sapien quam sed.')

isNum = False

for i in range(len(phoneNo)):
    sweep = phoneNo[i:i+12]

    if numCheck(sweep):
        print('We found a number: ' + sweep)
        isNum = True

if not isNum:
        print('We couldn\'t find a number')

结果:

We found a number: 124-567-6893
We found a number: 234-574-1111

Traceback (most recent call last):
  File "/Users/johnny/Desktop/Python/testing .py", line 26, in <module>
    if numCheck(sweep):
  File "/Users/johnny/Desktop/Python/testing .py", line 7, in numCheck
    if len(digits[1]) != 3:
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

问题出在这部分:

for i in range(len(phoneNo)):
    sweep = phoneNo[i:i+12]

您想要做这样的事情:

for i in range(len(phoneNo)-12):
    sweep = phoneNo[i:i+12]

这是因为在此方法的最后12次迭代中,您试图将其切到列表的末尾。