- 使用replace替换字符串
- 使用re.sub替换字符串
import re
from calendar import month_abbr
text = 'yeah, but no, but yeah, but no, but yeah'
print(text.replace('yeah', 'yep'))
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
print(re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', text))
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
print(datepat.sub(r'\2-\1-\2', text))
def change_date(m):
mon_name = month_abbr[int(m.group(1))]
return '%s %s %s' % (m.group(2), mon_name, m.group(3))
print(datepat.sub(change_date, text))
newtext, n = datepat.subn(r'\2-\1-\2', text)
print(newtext)
print(n)
yep, but no, but yep, but no, but yep
Today is 2012-11-27. PyCon starts 2013-3-13.
Today is 27-11-27. PyCon starts 13-3-13.
Today is 27 Nov 2012. PyCon starts 13 Mar 2013.
Today is 27-11-27. PyCon starts 13-3-13.
2