某软件中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()方法做字符串替换,利用正则表达式的捕获组,捕获每个部分内容,在替换字符串中调整各个捕获组的顺序。该方法代码如下:
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) |

