Python3 调整字符串中文本格式,re.sub

某软件中log文件,其中日期格式为‘yyyy-mm-dd’:
……
2016-05-23 10:59:26 status unpacked python3-pip:all
2016-05-23 10:59:26 status half-configured python3-pip:all
2016-05-23 10:59:26 status installed python3-pip:all
2016-05-23 10:59:26 status configue python3-pip:all
……
我们想把其中的日期改为美国日期的格式‘mm/dd/yyyy’.
‘2016-05-23’ =>‘05/23/2016’,应如何处理?

解决方案:使用正则表达式re.sub()方法做字符串替换,利用正则表达式的捕获组,捕获每个部分内容,在替换字符串中调整各个捕获组的顺序。该方法代码如下:

Python
# -*- coding: utf-8 -*- __author__ = 'songhao' import re tt = """ 2016-05-23 10:59:26 status unpacked python3-pip:all 2016-05-23 10:59:26 status half-configured python3-pip:all 2016-05-23 10:59:26 status installed python3-pip:all 2016-05-23 10:59:26 status configue python3-pip:all""" s = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/re-sub" title="View all posts in re.sub" target="_blank">re.sub</a></span>('(\d{4})-(\d{2})-(\d{2})', r'\2/\1/\3', tt) ss = <span class="wp_keywordlink_affiliate"><a href="https://www.168seo.cn/tag/re-sub" title="View all posts in re.sub" target="_blank">re.sub</a></span>("(?P<year>\d{4})-(?P<moth>\d{2})-(?P<day>\d{2})", r"\g<moth>/\g<year>/\g<day>", tt) print(s) print(ss)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# -*- coding: utf-8 -*-
__author__ = 'songhao'
import re
 
tt = """
2016-05-23 10:59:26 status unpacked python3-pip:all
2016-05-23 10:59:26 status half-configured python3-pip:all
2016-05-23 10:59:26 status installed python3-pip:all
2016-05-23 10:59:26 status configue python3-pip:all"""
 
s = re . sub ( '(\d{4})-(\d{2})-(\d{2})' , r '\2/\1/\3' , tt )
 
ss = re . sub ( "(?P<year>\d{4})-(?P<moth>\d{2})-(?P<day>\d{2})" , r "\g<moth>/\g<year>/\g<day>" , tt )
print ( s )
print ( ss )



  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值