這篇文章主要介紹了python字符串替換re.sub()實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
re.sub(pattern, repl, string, count=0, flags=0)
pattern可以是一個字符串也可以是一個正則,用于匹配要替換的字符,如果不寫,字符串不做修改。/1 代表第一個分組
repl是將會被替換的值,repl可以是字符串也可以是一個方法。如果是一個字符串,反斜杠會被處理為逃逸字符,如/n會被替換為換行,等等。repl如果是一個function,每一個被匹配到的字段串執行替換函數。
/g<1> 代表前面pattern里面第一個分組,可以簡寫為/1,/g<0>代表前面pattern匹配到的所有字符串。
count是pattern被替換的最大次數,默認是0會替換所有。有時候可能只想替換一部分,可以用到count
實例1:
a = re.sub(r'hello', 'i love the', 'hello world')print(a)<br data-filtered="filtered">'i love the world' #hello world里面的hello被 i love the替換
實例2:
>>> a = re.sub(r'(/d+)', 'hello', 'my numer is 400 and door num is 200')>>> a'my numer is hello and door num is hello' #數字400 和 200 被hello替換
實例3:
a = re.sub(r'hello (/w+), nihao /1', r'emma','hello sherry, nihao sherry')>>> a'emma' #/1代表第一個分組的值即sherry,因為有兩個sherry,所以用/1可以指代第二個,這樣整個字符串被emma替換
示例4:
>>> a = re.sub('(/d{4})-(/d{2})-(/d{2})', r'/2-/3-/1', '2018-06-07')>>> a'06-07-2018'>>> a = re.sub('(/d{4})-(/d{2})-(/d{2})', r'/g<2>-/g<3>-/g<1>', '2018-06-07')>>> a'06-07-2018' #/2 和 /g<2> 指代的的都是前面的第二個分組
示例5:
import redef replace_num(str): numDict = {'0':'〇','1':'一','2':'二','3':'三','4':'四','5':'五','6':'六','7':'七','8':'八','9':'九'} print(str.group()) return numDict[str.group()]my_str = '2018年6月7號'a = re.sub(r'(/d)', replace_num, my_str)print(a) #每次匹配一個數字,執行函數,獲取替換后的值
re.subn(pattern, repl, string, count=0, flags=0)
和sub()函數一樣,只是返回的是一個tuple,替換后的字符串和替換的個數
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答