python 4-3 如何调整字符串中文本格式re.sub(p,r'\1/\2',str1)/re.sub('(?P<Name>p),'\g<Name>',str1)
来源:互联网 发布:襄阳网络电视台台湾周 编辑:程序博客网 时间:2024/05/16 06:11
python 4-3 如何调整字符串中文本格式re.sub(p,r’\1/\2’,str1)/re.sub(‘(?Pp),’\g’,str1)
解决方案:
使用正则表达式re.sub()方法做字符串替换,利用正则表达式的捕获组,
捕获的每个部分内容,在替换字符串中调整各个捕获组的顺序
需要将2017-01-22转换成01-22-2017
s = "2017-01-22"print re.sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",s)print re.sub("(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})","\g<month>/\g<day>/\g<year>",s)01/22/201701/22/2017
需要将book.txt 中的书籍价格都提高5%
cat book.txt booka 23.99bookb 12.59bookc 19.99f = open("book.txt").read()def func(m): price = m.group(2) price = float(price) * 1.05 return "%s %.2f"%(m.group(1),price)print re.sub("(\w+)\s+(\d+.?\d*)",func,f)
0 0
- python 4-3 如何调整字符串中文本格式re.sub(p,r'\1/\2',str1)/re.sub('(?P<Name>p),'\g<Name>',str1)
- python re.compile(?P<name>)
- python-13-如何调整字符串中文本的格式?sub函数
- python re sub
- python re.sub
- Python re.sub
- re sub
- re.sub
- python re.sub 正则匹配
- 详解Python中re.sub
- python:re.sub简要分析
- 详解Python中re.sub
- 详解Python中re.sub
- 正则表达式(?P<name>...)
- python中使用re.sub更换倒数第一个字符串
- python中的正则替换字符串函数re.sub
- Python--详解Python中re.sub
- python re模块 sub方法介绍
- qt .prl文件作用
- python笔记
- Linux/Android——usb触摸屏驱动 - usbtouchscreen (一)
- IDA的string,section查看及代码重定位
- Toolbar随着ScrollView滑动透明度渐变效果实现
- python 4-3 如何调整字符串中文本格式re.sub(p,r'\1/\2',str1)/re.sub('(?P<Name>p),'\g<Name>',str1)
- FastScrollView实现及其setContentSize与setInnerContainerSize理解
- logcat内容备份
- 用 Docker 创建 serverless 应用
- Lotus and Characters
- oracle查看被锁的表和解锁
- 分解质因数
- ioncube加密与解密 php代码
- MFC MainFrame中的 OnShowWindow一个bug