如何在 Python 中搜索和替换文本?
pythonserver side programmingprogramming更新于 2026/2/15 14:04:17
问题
您想要搜索并替换字符串中的文本模式。
如果我们有一个非常简单的文字模式,使用 str.replace() 方法是最佳解决方案。
示例
def sample():
yield 'Is'
yield 'USA'
yield 'Colder'
yield 'Than'
yield 'Canada?'
text = ' '.join(sample())
print(f"Output \n {text}")
输出
美国比加拿大冷吗?
我们先看看如何搜索文本。
# 搜索精确文本
print(f"Output \n {text == 'USA'}")
输出
False
我们可以使用基本字符串方法搜索文本,例如 str.find()、str.endswith()、str.startswith()。
# 文本以...开头
print(f"Output \n {text.startswith('Is')}")
输出
True
# 文本以...结尾使用
print(f"Output \n {text.startswith('Is')}")
输出
True
# 使用 find 搜索文本
print(f"Output \n {text.find('USA')}")
输出
3
如果要搜索的输入文本更复杂,那么我们可以使用正则表达式和 re 模块。
# 让我们创建一个字符串格式的日期 date1 = '22/10/2020'
# 让我们检查文本是否包含多于 1 位数字。
# \d+ - 匹配一位或多位数字
import re
if re.match(r'\d+/\d+/\d+', date1):
print('yes')
else:
print('no')
yes
现在,回到替换文本。如果要替换的文本和字符串很简单,则使用 str.replace()。
输出
print(f"Output \n {text.replace('USA', 'Australia')}")
输出
Is Australia Colder Than Canada?
如果要搜索和替换的模式很复杂,那么我们可以利用 re 模块中的 sub() 方法。
sub() 的第一个参数是要匹配的模式,第二个参数是替换模式。
在下面的示例中,我们将找到 dd/mm/yyyy 中的日期字段,并以 yyyy-dd-mm 格式替换它们。反斜杠数字(例如 \3)表示模式中的捕获组号
import re
sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'
# 句子
replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)
print(f"Output \n {replaced_text}")
输出
Date is 2020-22-11. Tommorow is 2020-23-11.
另一种方法是先编译表达式以获得更好的性能。
输出
pattern = re.compile(r'(\d+)/(\d+)/(\d+)')
replaced_pattern = pattern.sub(r'\3-\1-\2', sentence)
print(f"Output \n {replaced_pattern}")
输出
Date is 2020-22-11. Tommorow is 2020-23-11.
re.subn() 将为我们提供替换文本的次数。
输出
output, count = pattern.subn(r'\3-\1-\2', sentence)
print(f"Output \n {output}")
输出
Date is 2020-22-11. Tommorow is 2020-23-11.
输出
print(f"Output \n {count}")
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

