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.
help(re.sub)

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

 

转载于:https://www.cnblogs.com/smulngy/p/8871816.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值