如何在不使用内置替换功能的情况下用另一个单词替换字符串中的单词?

时间:2019-03-22 11:16:06

标签: python python-3.x

我正在尝试自行在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

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

这是我假设最多只出现一次的方式:

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

答案 1 :(得分:0)

这是一种方法:

def replace(s, s1, s2):
    tokens = s2.split()
    if s in tokens:
       tokens[tokens.index(s)] = s1
    return ' '.join(tokens)

这是测试输出:

>>> def replace(s, s1, s2):
...     tokens = s2.split()
...     if s in tokens:
...        tokens[tokens.index(s)] = s1
...     return ' '.join(tokens)
... 
>>> replace("with", "by" , "Don't play without your friends")
"Don't play without your friends"
>>> 

答案 2 :(得分:0)

这是创建替换函数的另一种方法:

replacy = ("with", "by" , "Don't play without your friends")
def replace_all (target,find,replace):
  return replace.join(target.split(find))
target = replacy[2]
find = replacy[0]
replace = replacy[1]
print(replace_all(target, find, replace))

希望它会有所帮助:)

答案 3 :(得分:-2)

您可以使用正则表达式:

>>> import re
>>> def replace(s1, s2, text):
...     text = re.sub(s1, s2, text)
...     return text
...
>>> print(replace("with", "by" , "Don't play without your friends"))
Don't play byout your friends