問題背景
從許多中文的參考文獻上,rstrip() 函數的功能被簡單描述爲 :刪除字符串末尾的指定字符(默認爲空格)
,我的理解是,直接去掉末尾指定的字符序列,如我傳入的是d
,則會去掉末尾的字符d
(如果存在),如果傳入了字符ad
,則去掉末尾的字符ad
(如果存在),直到我們開發的服務遇到了一個非常奇怪的bug之後,下面是奇怪問題的復現過程:
>>> s = 'hello_world'
>>> s.rstrip('d') # 去除末尾的字符d
'hello_worl'
>>>
>>> s.rstrip('ld') # 去除末尾的字符 ld
'hello_wor'
>>>
>>> s.rstrip('ad') # 去除末尾字符 ad
'hello_worl' # ??? 爲什麼 d 被去掉了?
>>>
問題解決
在查了N多的中文參考資料之後,一直沒找到出現此現象的原因,於是我拜讀了一下python官方的文檔:https://docs.python.org/2/library/string.html
官方文檔的說明是:Return a copy of the string with trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the end of the string this method is called on.
簡單的翻譯一下,其意思就是去掉字符串末尾的指定字符,如果傳入的字符爲空,則去掉字符串末尾的空格,但是我們忽略了重點內容:the characters in the string will be stripped from the end of the string this method is called on,這裏面有兩個the string
,第一個the string
指的是用戶傳入的字符串,如上面的d
、ld
、ad
,而第二個the string
指的是需要處理的string,這樣理解之後,rstrip的功能就徹底明確了,其功能準確的描述就是:刪除字符串末尾指定的字符中任意字符,如果爲空,則刪除字符串末尾的空格
提到了rstrip,就不得不提起lstrip,lstrip和rstrip功能類似,唯一的區別就是rstrip去掉的是字符串末尾的指定字符,而lstrip去掉的是字符開頭的指定字符。
總結一下
rstrip和lstrip方法刪除的不是傳入的整個字符,而是以單個字符爲單位刪除,如果你傳入了一段字符串,如果這段字符串中任何一個字符出現在需刪除字符串的開頭或末尾,則都將會被刪除。如:
>>> s = 'helloworlld'
>>> s.rstrip('ld')
'hellowor'