题解 | 单词替换
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7?tpId=40&tqId=21377&rp=1&difficulty=&judgeStatus=&tags=/question-ranking
import sys
import re
if __name__=='__main__':
it=iter(sys.stdin)
while 1:
try:
line=next(it).strip()
old=next(it).strip()
pattern='\\b('+old+')\\b'
new=next(it).strip()
def repl(obj):
if obj.group(1) is not None:
return new
ans=re.sub(pattern,repl,line)
print(ans)
except:
break
使用正则表达式进行替换,将待替换单词精准提取出分组,直接替换分组
查看20道真题和解析