Python正则表达式re模块 sub 函数用法

Python的re模块中,函数re.sub(pattern, repl, string, count=0, flags=0),是用来将字符串替换成其他字符串的。
text = "apple's price is $12,orange's price is $22"
# 将所有价格(数字)替换为0
ret = re.sub('\d+','0',text) 
print(ret)

结果为apple's price is $0,orange's price is $0

sub函数还有个count的参数,我们可以传数字进去,传的数字多大代表替换多少个字符串。例如上例中,我们只将第一个价格替换为0

text = "apple's price is $12,orange's price is $22"
ret = re.sub('\d+','0',text,1)

结果为apple's price is 0,orange's price is $22

注意:

sub的count参数要在要被替换的字符串string,本例中就是text之后。否则报错

1.如果这样写

ret = re.sub('\$\d+','0',1,text) 就会报错

TypeError: 'str' object cannot be interpreted as an integer

对照sub(pattern, repl, string, count=0, flags=0),第三个位置应该是要被替换的字符串text,此处是数字。故报错

2.如果用关键字参数来传count呢?例如

ret = re.sub('\$\d+','0',count=1,text) 也报了错

SyntaxError: positional argument follows keyword argument

位置参数和关键字参数的顺序反了。这是该函数本来定义的,我们不能擅自修改他们的顺序

故改为ret = re.sub('\$\d+','0',text,1) 或ret = re.sub('\$\d+','0',text,count=1)

这样就正常运行了。结果也是正确的。

apple's price is 0,orange's price is $22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值