如何使用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
答案 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'