如何用Python來進行查詢和替換一個文字字串?
阿新 • • 發佈:2019-02-04
可以使用sub()方法來進行查詢和替換,sub方法的格式為:sub(replacement, string[, count=0])
replacement是被替換成的文字
string是需要被替換的文字
count是一個可選引數,指最大被替換的數量
例子:
import re
p = re.compile(‘(blue|white|red)’)
print(p.sub(‘colour’,'blue socks and red shoes’))
print(p.sub(‘colour’,'blue socks and red shoes’, count=1))
輸出:
colour socks and colour shoes
colour socks and red shoes
subn()方法執行的效果跟sub()一樣,不過它會返回一個二維陣列,包括替換後的新的字串和總共替換的數量
例如:
import re
p = re.compile(‘(blue|white|red)’)
print(p.subn(‘colour’,'blue socks and red shoes’))
print(p.subn(‘colour’,'blue socks and red shoes’, count=1))
輸出
(‘colour socks and colour shoes’, 2)
(‘colour socks and red shoes’, 1)