在 Python 中搜索和替換


使用正則表示式的最重要重寫方法之一是sub

語法

re.sub(pattern, repl, string, max=0)

此方法會將所有 RE string 中的 pattern 替換為 repl ,除非提供了 max,否則會替換所有出現的例項。此方法會返回修改後的字串。

示例

 現場演示

#!/usr/bin/python
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print "Phone Num : ", num

輸出

在執行以上程式碼時,會產生以下結果:

Phone Num : 2004-959-559
Phone Num : 2004959559

更新日期:2020 年 1 月 30 日

251 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.