首页 > 解决方案 > 如何在不使用内置替换功能的情况下用另一个单词替换字符串中的单词?

问题描述

我正在尝试自己在 python 中重新创建“替换”功能,但我很难过。

我的函数需要三个输入,第三个字符串中第一个字符串的出现被第二个字符串替换。

例子:

replace("with", "by" , "Don't play without your friends")
Result: ("Don't play byout your friends")

到目前为止我尝试过这个,但它不起作用,我想我把它复杂化了。

def replace(s, s1, s2):
    finall = list()
    l1 = s2.split()
    length_replace = len(s1)+1
    newlist = list()
    for i in range(len(l1)):
        if (s in l1[i]):
            newlist = list(l1[i])
            s = newlist[length_replace:]
            s = ''.join(s)
            final = s1 + s
            l1[i-1:i+1]= [final]
    return l1

任何帮助表示赞赏。

标签: pythonpython-3.x

解决方案


假设最多只出现一次,我会这样做:

def replace(source, match, replacing):
    result = None
    for i in range(0, len(source) - len(match)):
        if source[i:i+len(match)] == match:
            result = source[:i] + replacing + source[i+len(match):]
            break
    if not result:
        result = source
    return result


replace("Don't play without your friends", "with", "by")
# "Don't play byout your friends"

对于不止一次出现,您可以递归地编写它并提醒您source或包含一些临时变量来存储先前迭代的聚合结果,例如:

def replace(source, match, replacing):
    result = ''
    i, j = 0, 0
    while i < len(source) - len(match):
        if source[i:i+len(match)] == match:
            result += source[j:i] + replacing
            i += len(match)
            j = i
        else:
            i += 1
    result += source[j:]
    return result


replace('To be or not to be, this is the question!', 'be', 'code')
# 'To code or not to code, this is the question!'

replace('To be or not to be, this is the question!', 'is', 'at')
# 'To be or not to be, that at the question!'

并且只是为了看到它的行为类似于str.replace()函数:

source = 'To be or not to be, this is the question!'
match = 'is'
replacing = 'at'
replace(source, match, replacing) == source.replace(match, replacing)
# True

推荐阅读