【问题标题】:User defined function for replace() in python?python中replace()的用户定义函数?
【发布时间】:2019-11-15 21:08:02
【问题描述】:

我正在尝试编写一个用户定义的函数,以在不使用 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

【问题讨论】:

  • find_sub 是什么?
  • find_sub 是一个用户定义的函数,它与python中的find()函数做同样的事情,返回一个正在寻找的子字符串的起始索引。

标签: python python-3.x string replace


【解决方案1】:

为了消除混淆变量,我用find 替换了您不受支持的find_sub 调用,将您的无限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 用于不一致的目的。

【讨论】:

  • 我希望这里的所有作业问题都以这种方式回答。只是解释问题的完美示例,但需要进一步的工作和理解。
  • 谢谢。许多家庭作业问题不适用于这种处理。虽然 OP 没有遵循所有的发布指南,但存在足够小的功能差距和足够小的问题,一个 print 和一点指导就足够了。
猜你喜欢
  • 2021-12-23
  • 2019-02-14
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 2015-07-12
  • 2017-09-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多