如何在 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

更新於: 2020-11-10

621 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.