python - 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
解决方案
这是因为 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
推荐阅读
- r - 在折线图 R 中显示值
- android - Room 无法验证数据完整性,即使在卸载应用程序然后重新安装后也是如此
- c++ - C++ 上的并行并不像 C# 那样快
- verilog - 左移直到 MSB 为 1:超出循环计数限制。条件永远不会是假的
- powershell - 记录从单个父 ps 脚本调用的多个子 ps 脚本的输出的最佳简单方法是什么?
- c - 如何删除C中的特定记录
- r - 如何按一列分组并获取其他列的方法
- javascript - js类返回未定义的对象
- html - CSS区分悬停在元素上和它的 ::before 伪元素
- javascript - 在制作 Leaflet 地图时,如何将 GeoJSON 坐标拉取并转换为 latLng?