In the code below, s refers to a string (although I have tried converting it to a list and I still have the same problem).
s = "".join(s)
if s[-1] == "a":
s += "gram"
Run Code Online (Sandbox Code Playgroud)
我在字符串中的最后一项是字母"a",然后程序需要将字符串"gram"添加到字符串's'表示的末尾.
例如输入:
s = "insta"
Run Code Online (Sandbox Code Playgroud)
输出:
instagram
Run Code Online (Sandbox Code Playgroud)
但我不断得到一个IndexError,任何想法为什么?
如果s是空字符串s[-1]导致IndexError:
>>> s = ""
>>> s[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)
而不是s[-1] == "a",您可以使用s.endswith("a"):
>>> s = ""
>>> s.endswith('a')
False
>>> s = "insta"
>>> s.endswith('a')
True
Run Code Online (Sandbox Code Playgroud)
如果s是空的,则没有最后一个字母要测试:
>>> ''[-1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Run Code Online (Sandbox Code Playgroud)
str.endswith()改为使用:
if s.endswith('a'):
s += 'gram'
Run Code Online (Sandbox Code Playgroud)
str.endswith()不不,当字符串为空抛出一个异常:
>>> 'insta'.endswith('a')
True
>>> ''.endswith('a')
False
Run Code Online (Sandbox Code Playgroud)
或者,使用切片也可以:
if s[-1:] == 'a':
Run Code Online (Sandbox Code Playgroud)
因为切片总是返回一个结果(至少是一个空字符串),但str.endswith()对于它对代码的随意读者所做的操作更为明显.
| 归档时间: |
|
| 查看次数: |
57 次 |
| 最近记录: |