首页 > 解决方案 > Python 字符串索引超出范围,s[0] 和 s[:1] 之间的差异

问题描述

您好我是Python新手,正在尝试实现去除两端空格的功能。

trim_1()工作完美,但使用时出现此错误trim_2()

IndexError: string index out of range 

所以s[:1]s[0]不是一回事吗?为什么s[:1]有效而s[0]无效?任何人都可以对此有所了解吗?

def trim_1(s) :
    while s[:1]  == ' ':
        s= s[1:]
    while s[-1:] == ' ':
        s= s[:-1]
    return s


def trim_2(s) :
    while s[0] == ' ':
        s= s[1:]
    while s[-1] == ' ':
        s= s[:-1]
    return s

标签: pythonpython-3.xstringslice

解决方案


这是因为 Python 可以容忍切片的越界索引,而不能容忍列表/字符串本身的越界索引,如下所示:

>>> ''[:1] # works even though the string does not have an index 0
''
>>> ''[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

推荐阅读