首页 > 解决方案 > 您好,我的任务是编写函数并通过测试。我只能通过一项测试,有人可以帮助我完成第二项测试吗?

问题描述

我的任务是编写函数 def myreplace(old, new, s): 并通过测试。我可以通过第一个测试,但我不能通过第二个测试,因为有很多空格。有没有办法做到这一点?

def myreplace(old, new, s):
    # Replace all occurrences of old with new in s...
    new_s = ""
    for i in s.split():
        s.split(old)
        new_s = new.join(s.split(old))
    return new_s


test(myreplace(",", ";", "this, that, and some other thing") ==
         "this; that; and some other thing")
test(myreplace(" ", "**",
                   "Words will now      be  separated by stars.") ==
         "Words**will**now**be**separated**by**stars.")

标签: python

解决方案


这个怎么样:

def myreplace(old, new, s):
    # Replace all occurrences of old with new in s...
    if old == ' ':
        return new.join(s.split())
    else:
        return new.join(s.split(old))

推荐阅读