python 在字符串中查找匹配项并将其替换为替换字符串,直到没有匹配字符串。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 在字符串中查找匹配项并将其替换为替换字符串,直到没有匹配字符串。相关的知识,希望对你有一定的参考价值。

# Question 7: Find and Replace

# For this question you need to define two procedures:
#  make_converter(match, replacement)
#     Takes as input two strings and returns a converter. It doesn't have
#     to make a specific type of thing. It can
#     return anything you would find useful in apply_converter.
#  apply_converter(converter, string)
#     Takes as input a converter (produced by make_converter), and
#     a string, and returns the result of applying the converter to the
#     input string. This replaces all occurrences of the match used to
#     build the converter, with the replacement.  It keeps doing
#     replacements until there are no more opportunities for replacements.


def make_converter(match, replacement):
    convert = [match, replacement]
    return convert

def apply_converter(converter, string):
    start = string.find(converter[0])
    # print start
    if start != -1:
        end = start + len(converter[0])
        string = string[:start] + converter[1] + string[end:]
        # print string
        return apply_converter(converter, string)
    return string

# For example,

c1 = make_converter('aa', 'a')
print apply_converter(c1, 'aaaa')
#>>> a

c = make_converter('aba', 'b')
print apply_converter(c, 'aaaaaabaaaaa')
#>>> ab

# Note that this process is not guaranteed to terminate for all inputs
# (for example, apply_converter(make_converter('a', 'aa'), 'a') would
# run forever).

以上是关于python 在字符串中查找匹配项并将其替换为替换字符串,直到没有匹配字符串。的主要内容,如果未能解决你的问题,请参考以下文章

python 查找字符串并将其替换

是否有一个 Excel 函数或脚本来查找和替换两个不同工作表中匹配的字段,并将其替换为第二个工作表中包含的另一个数据?

查找并替换 textarea 中的所有匹配字符串

PLSQL:在 xml 中查找标签值并将其替换为标签名称以创建示例数据

查找和替换数组中的对象(基于 id)

如何在IDEA中查找指定类的所有变量并将其替换为同名