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

时间:2012-09-13 05:19:19

标签: python

如何使用loop将单词替换为其他单词。例如,假设我有function名为“changeWords”,我希望此功能更改三个单词不能不应该 >,不能不应该不能。因此,输入该功能后,“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.”

我的尝试:

def stringChange(a):
a = ""
for line in stringChange("a"):
    line = text.replace("a","can't","can not")
    if not line: break
    return line

1 个答案:

答案 0 :(得分:4)

>>> 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'