题解 | 单词替换

单词替换

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

使用正则表达式进行替换,将待替换单词精准提取出分组,直接替换分组

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务