日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【python cookbook】【字符串与文本】5.查找和替换文本

發布時間:2023/12/18 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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.查找和替换文本的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。