Python-替换多个字符而没有.replace()

Tom*_*cik 3 python replace

任务是将任何字符串转换为没有内置字符串的任何字符串.replace()。我失败了,因为我从技术上忘记了空格也是一个字符串字符。首先,我将此字符串转换为列表,但是现在我看到了不必要的操作。但是,它仍然不起作用。

  1. 我可以将“猫”替换为“狗”
  2. 我可以将“ c”替换为“ dog”

我不能将“猫”替换为“狗”。

我尝试使用lambdazip,但我真的不知道该怎么做。你有什么线索吗?

string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"

def rplstr(string,old,new):
    """ docstring"""

    result = ''
    for i in string:
        if i == old:
            i = new
        result += i
    return result

print rplstr(string, old, new)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ans 5

此解决方案避免了效率不高的字符串连接。它创建一个片段列表,最后将它们连接在一起:

string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"

def rplstr(string, old, new):
    """ docstring"""

    output = []
    index = 0

    while True:
        next = string.find(old, index)

        if next == -1:
            output.append(string[index:])
            return ''.join(output)
        else:
            output.append(string[index:next])
            output.append(new)
            index = next + len(old)

print rplstr(string, old, new)
Run Code Online (Sandbox Code Playgroud)

给予:

string = "Alice has a cat, a cat has Alice."
old = "a cat"
new = "a dog"

def rplstr(string, old, new):
    """ docstring"""

    output = []
    index = 0

    while True:
        next = string.find(old, index)

        if next == -1:
            output.append(string[index:])
            return ''.join(output)
        else:
            output.append(string[index:next])
            output.append(new)
            index = next + len(old)

print rplstr(string, old, new)
Run Code Online (Sandbox Code Playgroud)