cookbook之字符串搜索和替换

参考

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
贴吧的提问

发布了482 篇原创文章 · 获赞 13 · 访问量 6097
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 撸撸猫 设计师: 设计师小姐姐

分享到微信朋友圈

×

扫一扫,手机浏览