Python——不使用.replace()函数替换多个字符

3
任务是将任何字符串转换为另一个字符串,但不能使用内置的.replace()函数。我失败了,因为我忘记了空格也是一个字符串字符。首先,我将这个字符串转换为列表,但现在我发现这样做是不必要的。然而,它仍然无法正常工作。
以下是我可以做到的替换:
  1. 我可以将"cat"替换为"dog"
  2. 我可以将"c"替换为"dog"
但我无法将"a cat"替换为"a 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)

2
你尝试过使用 re.sub 吗? - Avinash Raj
嗯...由于给定的字符串是不可变的,所以赋值并没有意义,因为你可以直接使用“return new”... - Claudiu
4个回答

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)

赋予:

Alice has a dog, a dog has Alice.

3
你可以逐个字符地遍历字符串,并测试它是否与你的old字符串的第一个字符匹配。如果匹配成功,保留此位置的索引,然后继续向下遍历字符,现在尝试匹配old的第二个字符。一直持续到匹配整个old字符串为止。如果完全匹配成功,则使用第一个字符匹配的索引和old字符串的长度来创建一个新字符串,其中包含插入new字符串的内容。
def replstr(orig, old, new):
    i = 0
    output = ''
    temp = ''
    for c in orig:
        if c == old[i]:
            i += 1
            temp += c
        else:
            i = 0
            if temp:
                output += temp
                temp = ''
            output += c
        if len(temp) == len(old):
            output += new
            temp = ''
            i = 0
    else:
        if temp:
            output += temp

Alice有一只狗,这只狗有一个阿拉伯名字。这就是我所拥有的,但可能只是代码中的一些小问题。一只猫被改成了一只狗。我会多次阅读你的代码。谢谢。 - Tom Wojcik
@TomWojcik 哦,是的,我漏掉了一行。已更新。 - Brendan Abel

2
你可以使用切片来完成它:
def rplstr(string, old, new):
    for i in xrange(len(string)):
        if old == string[i:i+len(old)]:
            string = string[:i] + new + string[i+len(old):]
    return string

1
我认为如果“新”字符串比“旧”字符串长,则字符串末尾的字母不会被测试。或者如果“新”字符串包含“旧”字符串。 - Brendan Abel
您,先生,懂得如何编程。谢谢。它运行完美,而且相对简单。 - Tom Wojcik

2
你可以使用正则表达式以简单和精简的方式来完成。
import re

my_string = "Alice has a cat, a cat has Alice."
new_string = re.sub(r'a cat', 'a dog', my_string)
print new_string

确实,它可以工作,但我的导师说我们不能使用任何内置方法,也不能使用正则表达式。 - Tom Wojcik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接