为什么我在一种情况下得到“索引器错误:字符串索引超出范围”而不是另一种情况?

2024-09-25 04:25:00 发布

您现在位置:Python中文网/ 问答频道 /正文

#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条件if len(string)>=2 and string[0]==string[-1]:和第二个函数中的{},我在代码中找不到区别


Tags: andtheinstringlenifdefmatch
1条回答
网友
1楼 · 发布于 2024-09-25 04:25:00

在第一种情况下,首先检查是否有足够的字符进行测试,而在第二种情况下则没有:

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

以及

^{pr2}$

然后传入一个空的字符串:

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表达式都不可能变成{}。在

请参见python文档中的Boolean expressions

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

相关问题 更多 >