前言
python 里面可以用 replace 實現簡單的替換字符串操作,如果要實現復雜一點的替換字符串操作,需用到正則表達式。
re.sub用於替換字符串中匹配項,返回一個替換后的字符串,subn方法與sub()相同, 但返回一個元組, 其中包含新字符串和替換次數。
sub介紹
Python 的 re 模塊提供了re.sub用於替換字符串中的匹配項,sub是substitute表示替換。
使用語法
sub(pattern, repl, string, count=0, flags=0)
- pattern:該參數表示正則中的模式字符串;
- repl:repl可以是字符串,也可以是可調用的函數對象;如果是字符串,則處理其中的反斜杠轉義。如果它是可調用的函數對象,則傳遞match對象,並且必須返回要使用的替換字符串
- string:該參數表示要被處理(查找替換)的原始字符串;
- count:可選參數,表示是要替換的最大次數,而且必須是非負整數,該參數默認為0,即所有的匹配都會被替換;
- flags:可選參數,表示編譯時用的匹配模式(如忽略大小寫、多行模式等),數字形式,默認為0。
sub示例-repl傳字符串
將字符串中的hello替換成數字123
import re #替換s中的hello為123,
s = "hello,world!!!"
print(re.sub(r'hello', "123", s)) #123,world!!!
把字符串中的連續數字替換成hello
import re # 把字符串中的連續數字替換成hello
s = "the number 0746-8798098"
print(re.sub(r'\d+', "hello", s)) # the number hello-hello
替換時間格式 01/11/2021 替換成 2021/01/11
import re # 替換時間格式 01/11/2021 替換成 2021/01/11
s = "today is 09-12-2021" day = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'\3-\2-\1', s) print(day) # today is 2021-12-09
# 也可以用g<3>-g<2>-g<1>
day2 = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'g<3>-g<2>-g<1>', s) print(day) # today is 2021-12-09
\3
和 \g<3>
指代的的都是前面匹配的第3個分組
repl傳函數對象
import re def fun(m): return m.group(1).title()+' '+m.group(2).title() #首字符大寫
str1='hello world ~~~~~~~~~' str1=re.sub(r"(\w+) (\w+)",fun,str1) print(str1) # Hello World ~~~~~~~~~
count替換次數
sub 加 count 參數可以控制要替換的次數,而且必須是非負整數,該參數默認為0,表示所有的匹配都會被替換;
import re # 替換字符串中的空格為123,只替換一次
s = "We are happy"
print(re.sub(" ", "123", s, count=1)) # We123are happy
subn方法使用
subn方法與sub()相同, 但返回一個元組, 其中包含新字符串和替換次數。
# 替換字符串中的空格為123
s = "We are happy"
print(re.subn(" ", "123", s)) #('We123are123happy', 2)