cookbook之字串搜尋和替換

2021-10-02 04:46:16 字數 1298 閱讀 6350

參考

import datetime

import re

from calendar import month_abbr

text =

'yeah, but no, but yeah, but no, but yeah'

print(text.replace(

'yeah','love'

))print(text)

date

= datetime.date.today(

)print(date)

date

= str(date)

print(type(date))

print(date)

print(date.replace(

'-','/'

))print(re.sub(r'(\d+)\-(\d+)\-(\d+)', r'\3/\2/\1',date))

def change_date(m):

mon_name = month_abbr[int(m.group(2))

]return

'今天是{}年{}{}日'.format(m.group(1),mon_name,m.group(3))

print(re.sub(r'(\d+)\-(\d+)\-(\d+)',change_date,date))

print(

'&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&'

)#疑惑,需要詢問別人

str1 =

date + '++++++++++++++' + date

print(str1)

res = re.compile(r'(\d+)\-(\d+)\-(\d+)'

)result, n = res.subn(r'\3/\2/\1',date)

print(result)

print(n)

print(

'**********************'

)text =

'today is 11/27/2012. pycon starts 3/13/2013.'

datepat = re.compile(r'(\d+)/(\d+)/(\d+)'

)newtext, n = datepat.subn(r'\3-\1-\2', text)

print(newtext)

print(n)

上面的疑惑已經解決,原來字串匹配模式是正確的,只是在使用subn 第二個引數寫成了 date 應該是 str1

貼吧的提問

cookbook之字串匹配和搜尋

參考 import datetime text yao,yao,qie ke nao,jian bing guo zi,yao,lai,yi,tao,print text.find tao 會返回第一次匹配到元素的下標 text2 datetime.date.today 顯示當前的年月日 text2...

字串搜尋

include include include includeusing namespace std char grid 100 100 word 100 int n m int x int y int xx yy void search if k len int main int t cin t ...

字串搜尋

include include include includeusing namespace std char grid 100 100 word 100 int n m int x int y int xx yy void search if k len int main int t cin t ...