Python中sub()用法

Python來進行查詢和替換一個文本字符串?

可以使用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)

發佈了70 篇原創文章 · 獲贊 57 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章