2014-10-01 158 views
0

試圖在最基本的級別使用rstrip(),但它似乎沒有任何效果。rstrip()對字符串沒有影響

例如:

string1='text&moretext' 
string2=string1.rstrip('&') 
print(string2) 

所需的結果: 文本

實際結果: 文本& moretext

使用Python 3,PyScripter

我缺少什麼?

回答

1

someString.rstrip(c)刪除字符串的所有c發生在結束。因此,例如

'text&&&&'.rstrip('&') = 'text' 

也許你想

'&'.join(string1.split('&')[:-1]) 

此分割字符串的分隔符「&」到字符串列表,刪除最後一個,再加入他們,用分隔符「&」。因此,例如,

'&'.join('Hello&World'.split('&')[:-1]) = 'Hello' 
'&'.join('Hello&Python&World'.split('&')[:-1]) = 'Hello&Python' 
+0

補充:http://www.tutorialspoint.com/python/string_rstrip.htm – mauris 2014-10-01 16:44:05

+0

謝謝,完美。說清楚你在用索引([:-1])做什麼? – traffikHam 2014-10-01 17:01:26

+0

刪除列表的最後一個成員。 – 2014-10-02 05:29:01