本文實(shí)例講述了Python實(shí)現(xiàn)的從右到左字符串替換方法。分享給大家供大家參考,具體如下:
一 . 前言
需要用到,但是發(fā)現(xiàn)python沒有從右邊開始替換的內(nèi)置方法,默認(rèn)的replace
只是從左邊開始,就索性自己寫個(gè),有需求的自己可以在此基礎(chǔ)上搞個(gè)python hack,給str增加個(gè)rreplace方法。
二. 實(shí)現(xiàn)
利用python 的其它內(nèi)置方法,11行代碼就可以了
1
2
3
4
5
6
7
8
9
10
11
|
def rreplace( self , old, new, * max ): count = len ( self ) if max and str ( max [ 0 ]).isdigit(): count = max [ 0 ] while count: index = self .rfind(old) if index > = 0 : chunk = self .rpartition(old) self = chunk[ 0 ] + new + chunk[ 2 ] count - = 1 return self |
學(xué)無(wú)止境,最后搜索發(fā)現(xiàn)有種核心代碼只有1行的實(shí)現(xiàn)方法
1
2
3
4
5
|
def rreplace( self , old, new, * max ): count = len ( self ) if max and str ( max [ 0 ]).isdigit(): count = max [ 0 ] return new.join( self .rsplit(old, count)) |
三. 用法
和 replace
基本一致
參數(shù):
self -- 源字符串。
old -- 將被替換的子字符串。
new -- 新字符串,用于替換old子字符串。
max -- 可選字符串, 替換不超過 max 次
返回:
被替換后的字符串
舉幾個(gè)用例比較下就清楚了:
1
2
3
4
5
|
print rreplace( "lemon tree" , "e" , "3" ) print rreplace( "lemon tree" , "e" , "3" , 1 ) print rreplace( "lemon tree" , "e" , "3" , 2 ) print rreplace( "lemon tree" , "tree" , "") print rreplace( "lemon tree" , "notree" , "notmatch" ) |
運(yùn)行結(jié)果:
l3mon tr33
lemon tre3
lemon tr33
lemon
lemon tree
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/c465869935/article/details/71106967