python 正则替换固定个数文字

从开始将aaa替换为bbb,总共替换3次,re.sub的参数count=0时表示全部替换

import re
# 原始文本
content = '111aaa222aaa333aaa444aaa555aaa'
name = 'aaa'
replace_name = 'bbb'
# 替换次数
count = 3
for i in range(count):
    content = re.sub(name, replace_name, content, count=1)
    print(content)

# print
# 111bbb222aaa333aaa444aaa555aaa
# 111bbb222bbb333aaa444aaa555aaa
# 111bbb222bbb333bbb444aaa555aaa

你可能感兴趣的:(python,re,python)