如果使用正则表达式,则可以使用以下命令指定单词边界
b:
import resentence = 'bean likes to sell his beans'sentence = re.sub(r'bbeanb', 'robert', sentence)# 'robert likes to sell his beans'
这里的’beans’不会更改(更改为’roberts’),因为末尾的’s’不是单词之间的边界:
b匹配空字符串, 仅 匹配单词的开头或结尾。
完整性的第二个替代:
sentence = re.sub(r'bbeansb', 'cars', sentence)# 'robert likes to sell his cars'
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)