问题描述
示例字符串:德里办公室管理"
我想用空格替换字符串中的 in.但是当我这样做时,s.replace('in',"")
,管理的输入也变成空白.
这只是一个示例.要替换的字符串和单词可能会有所不同.
有没有办法只替换完全匹配的内容?
您可以使用正则表达式 \bin\b
.\b
这里的意思是 字边界.\bin\b
将匹配被单词边界(空格、标点符号等)包围的 in
,而不是 in
换句话说.>>>>进口重新>>>re.sub(r'\bin\b', '', '德里办公室管理')'办公室行政德里'
请参阅re.sub
.
Example string: "office administration in delhi"
I want to replace in from the string with a blank. But when I do, s.replace('in',"")
, the in of administration also becomes blank.
This is just a sample. The string and the word to replace may vary.
Is there some way to replace only the exact match?
You can use regular expression \bin\b
. \b
here means word boundary. \bin\b
will match in
surrounded by word boundary (space, punctuation, ...), not in
in other words.
>>> import re
>>> re.sub(r'\bin\b', '', 'office administration in delhi')
'office administration delhi'
See re.sub
.
这篇关于替换python中的确切子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!