标签:
问题:对字符串中的文本做查找和替换
解决方案:
1、对于简单模式:str.replace(old, new[, max])
2、复杂模式:使用re模块中的re.sub(匹配的模式, newstring, oldstring[,替换个数])函数
3、re.subn()可以获得替换的总次数
# example.py # # Examples of simple regular expression substitution import 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 >>>
【python cookbook】【字符串与文本】5.查找和替换文本
标签:
原文地址:http://www.cnblogs.com/apple2016/p/5790780.html