为什么这会在python中给我一个索引错误?

时间:2013-09-07 09:37:55

标签: python string

在下面的代码中,s指的是一个字符串(虽然我已经尝试将其转换为列表但我仍然遇到同样的问题)。

s = "".join(s)
if s[-1] == "a":
    s += "gram"

我字符串中的最后一项是字母“a”,然后程序需要将字符串“gram”添加到字符串's'表示的末尾。

e.g。输入:

s = "insta"

输出:

instagram

但我一直在问IndexError,有什么想法吗?

2 个答案:

答案 0 :(得分:7)

如果s为空,则字符s[-1]会导致IndexError

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

您可以使用s[-1] == "a"

而不是s.endswith("a")
>>> s = ""
>>> s.endswith('a')
False
>>> s = "insta"
>>> s.endswith('a')
True

答案 1 :(得分:5)

如果s为空,则没有最后一个字母要测试:

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

改为使用str.endswith()

if s.endswith('a'):
    s += 'gram'
当字符串为空时,

str.endswith() 会引发异常:

>>> 'insta'.endswith('a')
True
>>> ''.endswith('a')
False

或者,使用切片也可以起作用:

if s[-1:] == 'a':

因为slice 总是返回一个结果(至少是一个空字符串),但str.endswith()对于它对代码的随意读者的作用更为明显。

相关问题