为什么在一个情况下会出现"IndexError: string index out of range",而在另一个情况下却没有?

2 投票
1 回答
4901 浏览
提问于 2025-04-17 13:38
#i couldnt find the difference in the code 
    >>> def match_ends(words):
     # +++your code here+++
     count=0
     for string in words:
      if len(string)>=2 and string[0]==string[-1]:
       count=count+1
     return count

>>> match_ends(['', 'x', 'xy', 'xyx', 'xx'])
2
>>> 
>>> def match_ends(words):
    # +++your code here+++
     count=0
     for string in words:
      if string[0]==string[-1] and len(string)>=2:
       count=count+1
     return count

>>> match_ends(['', 'x', 'xy', 'xyx', 'xx'])

   Traceback (most recent call last):
   File "<pyshell#26>", line 1, in <module>
   match_ends(['', 'x', 'xy', 'xyx', 'xx'])
   File "<pyshell#25>", line 5, in match_ends
   if string[0]==string[-1] and len(string)>=2:
   IndexError: string index out of range

我在这段代码里找不到其他的区别,除了第一个函数里的这个条件 if len(string)>=2 and string[0]==string[-1]: 和第二个函数里的这个条件 if string[0]==string[-1] and len(string)>=2:

1 个回答

6

在第一个例子中,你首先检查是否有足够的字符可以进行测试,而在第二个例子中则没有:

if len(string)>=2 and string[0]==string[-1]:

并且

if string[0]==string[-1] and len(string)>=2:

传入一个字符串:

match_ends(['', 'x', 'xy', 'xyx', 'xx'])

空字符串的长度是0,索引0的位置没有字符:

>>> len('')
0
>>> ''[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

在这个情况下,if的布尔表达式是从左到右进行评估的,而string[0]==string[-1]这个表达式会在len(string)>=2测试之前被评估,因此对于这个空字符串来说会失败。

在另一个版本中,len(string)>=2部分会先被评估,发现对于空字符串来说是False(0并不大于或等于2),然后Python就不需要再查看and表达式的另一半,因为无论第二部分的结果是什么,and表达式都不可能变成True

可以查看Python文档中的布尔表达式

表达式x and y首先会评估x;如果x为假,就返回它的值;否则,会评估y并返回结果。

撰写回答