python中replace()的用户定义函数?

时间:2019-11-15 21:08:02

标签: python python-3.x string replace

我正在尝试编写一个用户定义的函数,以用另一个字符串替换子字符串中所有出现的子字符串,而无需在python中使用replace()函数。 find_sub()是用户定义的函数,该函数返回要查找的子字符串的起始索引。 我已经尝试了以下代码,但没有终止。

def replace_sub(original_str, old_sub, new_sub):
    if find_sub(original_str, old_sub) == -1:
        print("Cannot replace this!")
        return -1
    else:
        substrings = []
        initial_pos = 0
        final_pos = find_sub(original_str, old_sub)
        while True:
            if final_pos == -1:
                part = original_str[initial_pos:]
                substrings.append(part)
                break
            part = original_str[initial_pos:final_pos]
            substrings.append(part)
            initial_pos = final_pos + len(old_sub)
            final_pos = find_sub(original_str[initial_pos:], old_sub)

        replaced_str = ""
        for part in substrings:
            replaced_str = part + new_sub
        return replaced_str

1 个答案:

答案 0 :(得分:1)

要删除混淆的变量,我将您不受支持的find_sub调用替换为find,将您的无限while转换为for,并插入了一个跟踪print ...简而言之,是标准的调试技术。

def replace_sub(...
    for iter in range(10):
    # while True:
        print(final_pos, original_str[initial_pos:], substrings)
        if final_pos == -1:
            part = original_str[initial_pos:]
            substrings.append(part)
            break
        part = original_str[initial_pos:final_pos]
        substrings.append(part)
        initial_pos = final_pos + len(old_sub)
        final_pos = original_str[initial_pos:].find(old_sub)

print(replace_sub("Now is the time", 'e', '3'))

输出讲述了这个故事:

9 Now is the time []
4  time ['Now is th']
4 s the time ['Now is th', '']
4 s the time ['Now is th', '', '']
4 s the time ['Now is th', '', '', '']
4 s the time ['Now is th', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '', '']
4 s the time ['Now is th', '', '', '', '', '', '', '', '']
3

使用基于original_str其余片段的索引对字符串下标进行了摸索,但是从字符串开头开始应用了它。您之所以循环,是因为第一次迭代后两者不再可互换。

回到设计,在纸上画出参考,并仔细更新哪个索引用于什么,以及如何计算适当的偏移量。考虑一个仅包含其余字符串的局部变量,而不是出于不一致的目的而尝试使用initial_pos