【python cookbook】【字符串与文本】5.查找和替换文本
生活随笔
收集整理的這篇文章主要介紹了
【python cookbook】【字符串与文本】5.查找和替换文本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題:對字符串中的文本做查找和替換
解決方案:
1、對于簡單模式:str.replace(old, new[, max])
2、復雜模式:使用re模塊中的re.sub(匹配的模式, newstring, oldstring[,替換個數])函數
3、re.subn()可以獲得替換的總次數
# example.py # # Examples of simple regular expression substitutionimport re#simple sample text1='yeah,but no,but yeah,but no,but yeah,but no,but yeah' print (text1.replace('yeah','yeh')) print (text1.replace('no','yes',2)) print ('---------------------------')# Some sample text text = 'Today is 11/27/2012. PyCon starts 3/13/2013.' datepat = re.compile(r'(\d+)/(\d+)/(\d+)') # (a) Simple substitution \3-表示匹配的模式中第3個模式組 print(datepat.sub(r'\3-\1-\2', text)) #等價于print (re.sub(r'(\d+)/(\d+)/(\d+)',r'\3-\1-\2', text)) print ('*****************************')
# (b) Replacement function 替換回調函數 from calendar import month_abbr def change_date(m):mon_name = month_abbr[int(m.group(1))]return '{} {} {}'.format(m.group(2), mon_name, m.group(3))print(datepat.sub(change_date, text)) print (re.sub(r'(\d+)/(\d+)/(\d+)',change_date, text)) print ('++++++++++++++++++++++++++++++++')
# 通過re.subn()獲取替換的總次數 newtext,n=datepat.subn(r'\3-\1-\2', text)
print (newtext)
print (n) >>> ================================ RESTART ================================ >>> yeh,but no,but yeh,but no,but yeh,but no,but yeh yeah,but yes,but yeah,but yes,but yeah,but no,but yeah --------------------------- Today is 2012-11-27. PyCon starts 2013-3-13. ***************************** Today is 27 Nov 2012. PyCon starts 13 Mar 2013. Today is 27 Nov 2012. PyCon starts 13 Mar 2013. ++++++++++++++++++++++++++++++++ Today is 2012-11-27. PyCon starts 2013-3-13. 2 >>>
?
轉載于:https://www.cnblogs.com/apple2016/p/5790780.html
總結
以上是生活随笔為你收集整理的【python cookbook】【字符串与文本】5.查找和替换文本的全部內容,希望文章能夠幫你解決所遇到的問題。