python去除字符串首尾的空格的代码问题

新手上路,请多包涵

def trim(s):

while s[:1]==' ':
    s=s[1:]
while s[-1:]==' ': #这一句替换成while s[-1]==' ',就处理不了
    s=s[:-1]       #‘’,‘   ’这样的字符串了,报错IndexError: string index out of range
return s
这是为何?
阅读 2.5k
2 个回答
If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j. If i or j is greater than len(s), use len(s). If i is omitted or None, use 0. If j is omitted or None, use len(s). If i is greater than or equal to j, the slice is empty.

以上是文档对切片的说明,可以看出使用切片时会先对冒号前后的i与j进行判断,所以''[-1:]中,判断后的i与j的值相等,故返回的切片为空,不会报错。
另外去除字符串首尾空格可以考虑直接用str自带的函数strip()

去空格用split不好么...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题