1. 使用字符串方法進行查找和替換
Python的字符串類 (str) 提供了簡單的查找和替換方法,如 find()、replace() 等。
示例:
text = "Hello, world!"
# 查找子字符串的位置
position = text.find("world")
print(position) # 輸出: 7
# 替換子字符串
new_text = text.replace("world", "Python")
print(new_text) # 輸出: "Hello, Python!"
2. 使用正則表達式進行查找和替換
Python的 re 模塊提供了強大的正則表達式支持,允許你進行復雜的模式匹配和替換操作。
導入 re 模塊:
import re
2.1. 使用 re.search() 進行查找
re.search() 用於查找第一個匹配的模式,並返回一個匹配對象。如果沒有找到匹配項,則返回 None。
示例:
text = "Hello, world!"
match = re.search(r"world", text)
if match:
print("Found:", match.group()) # 輸出: Found: world
else:
print("Not found")
2.2. 使用 re.sub() 進行替換
re.sub() 用於查找並替換所有匹配的模式。
示例:
text = "Hello, world!"
# 替換所有匹配的模式
new_text = re.sub(r"world", "Python", text)
print(new_text) # 輸出: "Hello, Python!"
2.3. 使用正則表達式進行復雜的匹配和替換
正則表達式可以使用各種元字符和模式來匹配更復雜的字符串。
示例:使用正則表達式替換所有數字為 #
text = "My phone number is 123-456-7890."
# 匹配所有數字
new_text = re.sub(r"\d", "#", text)
print(new_text) # 輸出: "My phone number is ###-###-####."
3. 兩者總結
str.replace()是一種簡單且高效的方法,適用於無需複雜匹配的替換。re.sub()結合正則表達式可以處理複雜的模式匹配和替換。
4. 計數
使用count函數
original_content = "OpenSNN是一個學習平台。OpenSNN提供了許多前端資源。"
updated_content = original_content.replace("OpenSNN", "開思通智網")
replace_count = original_content.count("OpenSNN")
print(f"替換後的內容: {updated_content}")
print(f"替換次數: {replace_count}")
使用re.subn函數
# 刪除 "[圖片:]url" 格式的內容
import re
updated_content, replace_count = re.subn(r'\[圖片:\]https?://[^\s]+', '', straaa)
print(f"替換後的內容: {updated_content}")
print(f"替換次數: {replace_count}")
【轉載自:】OpenSNN開思通智網 ---- “一起來O站,玩轉AGI!”
【官網:】https://w3.opensnn.com/
【原文鏈接:】https://w3.opensnn.com/os/article/10001360