Python中的sub函數是??re模塊(正則表(biao)達式模塊)中的一個(gè)非常重要的函數,它主要用于替換字符串中的匹配項,sub函數的基本語(yǔ)法如下:
(圖片來(lái)源網(wǎng)絡(luò ),侵刪)re.sub(patterヾ(′?`)?n, repl, string, count=0, flags=0)
參數說(shuō)明:
repl:替換的字符串,也可以是一個(gè)函數
string:要被查找替換的(′?ω?`)原始字符串
count:模式匹配后替換的最大次數,默認0表示替換所有的匹配
f??lags:標志位,用于控制正則表達式的匹配方式,如是否區分大小寫(xiě)等
下面通(′?ω?`)過(guò)幾個(gè)例子來(lái)詳細(′▽?zhuān)?)講解sub函數的使用方法:
1、(?_?;)基本替換
import retext = "Hello, Worヾ(′?`)?ld!"pa(′?`*)ttern = "World"replacement = "Python"new_text?? = re.sub(pattern, replacement,(′?_?`) text)print(new_text) # 輸出:Hello, Python!
2、使用函數作為替換
import redef replace_with_uppercase(match): return match.group(0).upper()text = "hello world"??pattern = "[az]+"new_text = re.sub(pattern, replace_with_uppercase, text)print(new_text) # 輸出:HELLO WORLD3、限制替換次數
import retext = "hello world, world"pattern = "world"replacement = "earth"只替換第一個(gè)匹配到的worldnew_(′▽?zhuān)?)text = re.sub(pattern, replacement, text, count=1)print(new_text) # 輸出:hello earth, world
import retext = "Hello, World!"pattern = "o"replacement = "0"不區分大小寫(xiě)進(jìn)行替換new_text = re.sub(pattern, replacement, text, flags=re.IGNORECA??SE)print(new_text) # 輸出:Hell0, W0rld!
Python中的sub函數是一個(gè)非常實(shí)用的函數,它可以幫助我們輕松地實(shí)現字符串的查找和替換,在實(shí)際開(kāi)發(fā)中,我們可以根據需要靈活地使用sub函數,以滿(mǎn)足各種不同的需求。