問題背景
從許多中文的參考文獻上,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'
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
