如何在 Python 中搜索和替换文本?
问题
您想在字符串中搜索并替换文本模式。
如果我们有一个非常简单的字面模式,使用 str.replace() 方法是一个最佳解决方案。
示例
def sample():
yield 'Is'
yield 'USA'
yield 'Colder'
yield 'Than'
yield 'Canada?'
text = ' '.join(sample())
print(f"Output \n {text}")输出
Is USA Colder Than Canada?
让我们首先看看如何搜索文本。
# search for exact text
print(f"Output \n {text == 'USA'}")输出
False
我们可以使用基本的字符串方法(如 str.find()、str.endswith()、str.startswith())来搜索文本。
# text start with
print(f"Output \n {text.startswith('Is')}")输出
True
# text ends with
print(f"Output \n {text.startswith('Is')}")输出
True
# search text with find
print(f"Output \n {text.find('USA')}")输出
3
如果要搜索的输入文本更复杂,则可以使用正则表达式和 re 模块。
# Let us create a date in string format date1 = '22/10/2020'
# Let us check if the text has more than 1 digit.
# \d+ - match one or more digits
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.'
# sentence
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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP