- Python - 文字處理
- Python - 文字處理簡介
- Python - 文字處理環境
- Python - 字串不變性
- Python - 對行排序
- Python - 段落重新格式化
- Python - 統計段落中的標記
- Python - 二進位制 ASCII 轉換
- Python - 字串作為檔案
- Python - 反向讀取檔案
- Python - 過濾重複單詞
- Python - 從文字中提取電子郵件
- Python - 從文字中提取 URL
- Python - 美化列印
- Python - 文字處理狀態機
- Python - 大寫和翻譯
- Python - 分詞
- Python - 刪除停用詞
- Python - 同義詞和反義詞
- Python - 文字翻譯
- Python - 單詞替換
- Python - 拼寫檢查
- Python - WordNet 介面
- Python - 語料庫訪問
- Python - 詞性標註
- Python - 組塊和組塊間隙
- Python - 組塊分類
- Python - 文字分類
- Python - 二元語法
- Python - 處理 PDF
- Python - 處理 Word 文件
- Python - 讀取 RSS 訂閱
- Python - 情感分析
- Python - 搜尋和匹配
- Python - 文字整理
- Python - 文字換行
- Python - 頻率分佈
- Python - 文字摘要
- Python - 詞幹提取演算法
- Python - 受約束搜尋
Python - 單詞替換
在文字處理中,替換整個字串或字串的一部分是一個非常常見的需求。replace() 方法返回一個字串的副本,其中舊字串的所有出現都被替換為新字串,可以選擇限制替換次數為 max。
以下是 replace() 方法的語法:
str.replace(old, new[, max])
引數
old - 要替換的舊子字串。
new - 將替換舊子字串的新子字串。
max - 如果提供了可選引數 max,則僅替換前 count 次出現。
此方法返回一個字串的副本,其中所有舊子字串的出現都被替換為新子字串。如果提供了可選引數 max,則僅替換前 count 次出現。
示例
以下示例演示了 replace() 方法的用法。
str = "this is string example....wow!!! this is really string"
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
結果
當我們執行以上程式時,它會產生以下結果:
thwas was string example....wow!!! thwas was really string thwas was string example....wow!!! thwas is really string
忽略大小寫的替換
import re
sourceline = re.compile("Tutor", re.IGNORECASE)
Replacedline = sourceline.sub("Tutor","Tutorialspoint has the best tutorials for learning.")
print (Replacedline)
當我們執行以上程式時,我們得到以下輸出:
Tutorialspoint has the best Tutorials for learning.
廣告