前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python笔记54-re正则匹配替换字符串(sub和subn)

python笔记54-re正则匹配替换字符串(sub和subn)

作者头像
上海-悠悠
发布2021-01-18 10:34:55
30.1K0
发布2021-01-18 10:34:55
举报

前言

python 里面可以用 replace 实现简单的替换字符串操作,如果要实现复杂一点的替换字符串操作,需用到正则表达式。 re.sub用于替换字符串中匹配项,返回一个替换后的字符串,subn方法与sub()相同, 但返回一个元组, 其中包含新字符串和替换次数。

sub介绍

Python 的 re 模块提供了re.sub用于替换字符串中的匹配项,sub是substitute表示替换。

  • pattern:该参数表示正则中的模式字符串;
  • repl:repl可以是字符串,也可以是可调用的函数对象;如果是字符串,则处理其中的反斜杠转义。如果它是可调用的函数对象,则传递match对象,并且必须返回要使用的替换字符串
  • string:该参数表示要被处理(查找替换)的原始字符串;
  • count:可选参数,表示是要替换的最大次数,而且必须是非负整数,该参数默认为0,即所有的匹配都会被替换;
  • flags:可选参数,表示编译时用的匹配模式(如忽略大小写、多行模式等),数字形式,默认为0。
代码语言:javascript
复制
def 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."""
    return _compile(pattern, flags).sub(repl, string, count)

sub使用示例

将字符串中的数字替换成*号

代码语言:javascript
复制
import re
'''
替换字符串中的数字为*号
'''
s = '作者-上海悠悠 QQ交流群:717225969 blog地址:https://www.cnblogs.com/yoyoketang/ 欢迎收藏'

new = re.sub("[0-9]", "*", s)
print(new)
# 作者-上海悠悠 QQ交流群:********* blog地址:https://www.cnblogs.com/yoyoketang/ 欢迎收藏

把字符串 s 中的每个空格替换成”%20”

代码语言:javascript
复制
import re
'''
替换s中的空格为%20
'''
s = "We are happy."
print(re.sub(r' ', "%20", s))

# We%20are%20happy.

把字符串中的连续数字替换成hello

代码语言:javascript
复制
import re
'''
把字符串中的连续数字替换成hello
'''
s = "the number 200-40-3000"
print(re.sub(r'[\d]+', "hello", s))

# the number hello-hello-hello

替换时间格式 01/11/2021 替换成 2021/01/11

代码语言:javascript
复制
import re
'''
替换时间格式 01/11/2021 替换成 2021/01/11
'''

s = "today is 01-11-2021."
day = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'\3-\2-\1', s)
print(day) # today is 2021-11-01.

# 也可以用g<3>-g<2>-g<1>
day2 = re.sub(r'(\d{2})-(\d{2})-(\d{4})', r'g<3>-g<2>-g<1>', s)
print(day) # today is 2021-11-01.

\3\g<3>指代的的都是前面匹配的第3个分组

repl传函数对象

匹配字符串中的数字加2

代码语言:javascript
复制
import re
'''
匹配字符串中的数字加2
'''

def addAge(match) ->str:
    '''返回匹配的值加2'''
    age = match.group()
    return str(int(age)+2)

s = 'my age is 20'
# repl 如果它是可调用的函数对象,则传递match对象,并且必须返回要使用的替换字符串
x = re.sub(r'[\d]+', addAge, s)
print(x)
# my age is 22

count替换次数

sub 加 count 参数可以控制要替换的最大次数,而且必须是非负整数,该参数默认为0,即所有的匹配都会被替换;

代码语言:javascript
复制
import re

'''
替换字符串中的空格为%20,只替换一次
'''
s = "We are happy."
print(re.sub(" ", "%20", s, count=1))

# We%20are happy.

subn方法使用

subn方法与sub()相同, 但返回一个元组, 其中包含新字符串和替换次数。

代码语言:javascript
复制
import re

'''
替换字符串中的空格为%20,只替换一次
'''
s = "We are happy."
x, n = re.subn(" ", "%20", s, )
print("替换后:", x)
print("替换次数: ", n)

运行结果 替换后:We%20are%20happy. 替换次数: 2

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-01-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始学自动化测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • sub介绍
  • sub使用示例
  • repl传函数对象
  • count替换次数
  • subn方法使用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档