4-3如何调整字符串中文本的格式
1、解决思路
这是字符串替换,用正则表达式找到原字符串的日期格式,将之替换成想要的格式,并且替换成的字符串不是固定的字符串
>>> import re
>>> help(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.
re.sub(‘\d{4}-\d{2}-\d{2}’,) 正则达式捕获
re.sub(‘(\d{4})-(\d{2})-(\d{2})’,r’\2/\3/1’,string) 第一个参数为正则表达式捕获组 从第一个括号开始分别为组1、组2、组3。第二个参数为替换描述字符串,“\1\2”作为相对位置使用为组1和组2。这里要使用原始字符串因为”\”具有转义作用,不想使用转义功能简单方式是使用“r”作为原始字符串。第三个参数为要替换的字符串内容
re.sub(‘(?P<year>\d{4})-(?P<month>\d{2})-(P<day>\d{2})’,r’\g<month>/\g<day>/\g<year>’,string)
?P<XXX>对组起名字 引用可以不使用相对位置而使用组的名字 \g<XXX>
2、实际解决
>>> import re
(1)打开文本并读取
>>> log = open(r"C:\视频\python高效实践技巧笔记\4 字符串处理相关话题\Modify string format.txt").read()
(2)查看读取的文本
>>> log '2016-05-23 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000\n2017-11-01 server 100.1.7.9 100.1.7.9 weight 20 maxconn 4000' >>> >>> print log 2016-05-23 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 2017-11-01 server 100.1.7.9 100.1.7.9 weight 20 maxconn 4000
(3)通过re.sub捕获组,捕获每一部分内容,在替换字符串中调整各个捕获组的内容,重新排版
>>>ret = re.sub('(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})', r'\g<month>/\g<day>/\g<year>',log)
(4)查看调整后的内容
>>> ret '05/23/2016 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000\n11/01/2017 server 100.1.7.9 100.1.7.9 weight 20 maxconn 4000' >>> print ret 05/23/2016 server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000 11/01/2017 server 100.1.7.9 100.1.7.9 weight 20 maxconn 4000
posted on 2018-04-18 09:01 石中玉smulngy 阅读(415) 评论(0) 编辑 收藏 举报