re.sub用法

re.sub用法

re.sub用于替换字符串中的匹配项。
下面一个例子将字符串中的空格 ’ ’ 替换成 ‘-’ :

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+', '-', text))
输出:JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

re.sub的函数原型为:re.sub(pattern, repl, string, count)
其中第二个函数是替换后的字符串;本例中为’-’
第四个参数指替换个数。默认为0,表示每个匹配项都替换。

把“ r’\s+’ ” 替换为“ r’is\s+’” 结果是把原句中的is改为了-。

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'is\s+', '-', text)
输出:JGood -a handsome boy, he -cool, clever, and so on...

改为 re.sub(r’\s+,\s+’, ', ', text),无改变。

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print(re.sub(r'\s+\.', '.', text))
输出:JGood is a handsome boy, he is cool, clever, and so on...

改为 re.sub(r’\s+,\s+’, ', ', text),boy后加三个逗号,三个逗号没有少,是空格发生了变化,…y, , , h… 替换为**…y, , h…**。

import re
 text="JGood is a handsome boy, , , he is cool, clever, and so on..."
print(re.sub(r'\s+,\s+', ', ', text))
输出:JGood is a handsome boy,, , he is cool, clever, and so on...

在原句每个空格之前加了空格

text = "JGood is a handsome boy  , he is cool  , clever  , and so on..."
print(re.sub(r'\s+,\s+', ',', text))
输出:“JGood is a handsome boy,he is cool,clever,and so on...”

re.sub(pattern, repl, string, count)中PATTERN的作用,找到text中与patern所匹配的形式,把text中与patern所匹配的形式以外的用repl代替。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值