4-3 如何调整字符串中文本的格式

实际案例:
某软件的log文件,其中的日期格式为'yyyy-mm-dd':
2017-05-03 10:59:30 status unpacked python3-pip all
2017-05-03 10:59:30 status half-configured python3-pip all
2017-05-03 10:59:30 configure python3-wheel:all 0.24.0-1
....

我们想把其中日期改为美国日期的格式'mm/dd/yyyy',
即'2017-05-03'->'05/03/2017',应该如何处理?

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

Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

解决方案:

import re
log = open('../static/mylog').read()

# 默认分组
res1 = re.sub('(\d{4})-(\d{2})-(\d{2})',r'\2/\3/\1',log)
print(res1)

# 给分组起别名
res2 = re.sub('(?P\d{4})-(?P\d{2})-(?P\d{2})',r'\g/\g/\g',log)
print(res2)

你可能感兴趣的:(4-3 如何调整字符串中文本的格式)