鍍金池/ 問答/Python/ python去除字符串首尾的空格的代碼問題

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
這是為何?
回答
編輯回答
萌二代
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自帶的函數(shù)strip()

2018年8月5日 01:42
編輯回答
空白格

去空格用split不好么...

2018年5月14日 21:17