正则表达式之 sub 替换字符

Python 的 re 模块提供了re.sub用于替换字符串中的匹配项

 语法:

re.sub(pattern, repl, string, count=0, flags=0)

参数:

  • pattern : 正则中的模式字符串。
  • repl : 替换的字符串,也可为一个函数。
  • string : 要被查找替换的原始字符串。
  • count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
 1 # coding=utf-8
 2 import re
 3 import logging
 4 
 5 # 删掉 Python的注释内容
 6 s = '2020-8-13 14:20:24 # 这是一个时间'
 7 
 8 logging.warning(re.sub(r'(#.*$)', '', s))
 9 
10 # 删掉 : 替换才能 -
11 s = '2020-8-13 14:20:24 # 这是一个时间'
12 
13 logging.warning(re.sub(r'(:)', '-', s))
案例

 以上实例执行结果如下:

WARNING:root:2020-8-13 14:20:24 
WARNING:root:2020-8-13 14-20-24 # 这是一个时间

repl 参数是一个函数

以下实例中将字符串中的匹配的数字乘以 2:

 1 # coding=utf-8
 2 import re
 3 import logging
 4 
 5 s = 'A1B2C55'
 6 
 7 
 8 def double(res):
 9     return str(int(res.group('value')) * 2)
10 
11 
12 logging.warning(re.sub('(?P<value>d+)', double, s))
案例

执行输出结果为:

WARNING:root:A2B4C110
原文地址:https://www.cnblogs.com/shangwei/p/13496202.html