問(wèn)題背景
從許多中文的參考文獻(xiàn)上,rstrip() 函數(shù)的功能被簡(jiǎn)單描述為 :
刪除字符串末尾的指定字符(默認(rèn)為空格)
,我的理解是,直接去掉末尾指定的字符序列,如我傳入的是
d
,則會(huì)去掉末尾的字符
d
(如果存在),如果傳入了字符
ad
,則去掉末尾的字符
ad
(如果存在),直到我們開(kāi)發(fā)的服務(wù)遇到了一個(gè)非常奇怪的bug之后,下面是奇怪問(wèn)題的復(fù)現(xiàn)過(guò)程:
>>> s = 'hello_world'
>>> s.rstrip('d') # 去除末尾的字符d
'hello_worl'
>>>
>>> s.rstrip('ld') # 去除末尾的字符 ld
'hello_wor'
>>>
>>> s.rstrip('ad') # 去除末尾字符 ad
'hello_worl' # ??? 為什么 d 被去掉了?
>>>
問(wèn)題解決
在查了N多的中文參考資料之后,一直沒(méi)找到出現(xiàn)此現(xiàn)象的原因,于是我拜讀了一下python官方的文檔:https://docs.python.org/2/library/string.html
官方文檔的說(shuō)明是: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.
簡(jiǎn)單的翻譯一下,其意思就是去掉字符串末尾的指定字符,如果傳入的字符為空,則去掉字符串末尾的空格,但是我們忽略了重點(diǎn)內(nèi)容:the characters in
the string
will be stripped from the end of
the string
this method is called on,這里面有兩個(gè)
the string
,第一個(gè)
the string
指的是用戶傳入的字符串,如上面的
d
、
ld
、
ad
,而第二個(gè)
the string
指的是需要處理的string,這樣理解之后,rstrip的功能就徹底明確了,其功能準(zhǔn)確的描述就是:刪除字符串末尾指定的字符中任意字符,如果為空,則刪除字符串末尾的空格
提到了rstrip,就不得不提起lstrip,lstrip和rstrip功能類似,唯一的區(qū)別就是rstrip去掉的是字符串末尾的指定字符,而lstrip去掉的是字符開(kāi)頭的指定字符。
總結(jié)一下
rstrip和lstrip方法刪除的不是傳入的整個(gè)字符,而是以單個(gè)字符為單位刪除,如果你傳入了一段字符串,如果這段字符串中任何一個(gè)字符出現(xiàn)在需刪除字符串的開(kāi)頭或末尾,則都將會(huì)被刪除。如:
>>> s = 'helloworlld'
>>> s.rstrip('ld')
'hellowor'
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

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