Python用循环替换函数中的多个单词?

2024-05-23 16:24:25 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用loop将一个词替换为另一个词。例如,假设我有一个名为“changeWords”的function”,我想让这个函数将三个单词不能不应该不要不能不应该不要。所以当输入函数时,“changeWords("I don't know how to do this")'应该返回”I do not know how to do this".

澄清:

changeWords(“I can't eat") -> “I can not eat"
changeWords(“I don't like swimming.”) -> “I do not like swimming.”
changeWords(“I shouldn't do that.”) -> “I should not do that.”

我的尝试:

^{pr2}$

Tags: to函数loopthatnotthisdocan
1条回答
网友
1楼 · 发布于 2024-05-23 16:24:25
>>> def changeWords(s):
        for old, new in (
                ("can't", "can not"),
                ("shouldn't", "should not"),
                ("don't", "do not"),
            ):    
            s = s.replace(old, new)
        return s

>>> changeWords("I don't know how to do this")
'I do not know how to do this'

相关问题 更多 >