替换string中第n次出现的子串

ale*_*kva 16 python string replace substring

我想替换字符串中第n个子串的出现.

必须有一些与我想做的事情相同的东西

mystring.replace("substring", 2nd)

实现这一目标的最简单,最恐怖的方法是什么?

为什么不重复:我不想使用正则表达式这种方法,我发现的类似问题的大多数答案只是正则表达式剥离或真正复杂的功能.我真的希望尽可能简单而不是正则表达式解决方案.

Pad*_*ham 18

您可以使用while循环str.find来查找第n个匹配项(如果它存在)并使用该位置创建新字符串:

def nth_repl(s, sub, repl, nth):
    find = s.find(sub)
    # if find is not p1 we have found at least one match for the substring
    i = find != -1
    # loop util we find the nth or we find no match
    while find != -1 and i != nth:
        # find + 1 means we start at the last match start index + 1
        find = s.find(sub, find + 1)
        i += 1
    # if i  is equal to nth we found nth matches so replace
    if i == nth:
        return s[:find]+repl+s[find + len(sub):]
    return s
Run Code Online (Sandbox Code Playgroud)

例:

In [14]: s = "foobarfoofoobarbar"

In [15]: nth_repl(s, "bar","replaced",3)
Out[15]: 'foobarfoofoobarreplaced'

In [16]: nth_repl(s, "foo","replaced",3)
Out[16]: 'foobarfooreplacedbarbar'

In [17]: nth_repl(s, "foo","replaced",5)
Out[17]: 'foobarfoofoobarbar'
Run Code Online (Sandbox Code Playgroud)


ale*_*kva 7

我使用简单的函数,它列出所有出现的位置,选择第 n 个位置并使用它将原始字符串拆分为两个子字符串。然后它替换第二个子字符串中的第一次出现并将子字符串连接回新字符串:

import re

def replacenth(string, sub, wanted, n):
    where = [m.start() for m in re.finditer(sub, string)][n-1]
    before = string[:where]
    after = string[where:]
    after = after.replace(sub, wanted, 1)
    newString = before + after
    print(newString)
Run Code Online (Sandbox Code Playgroud)

对于这些变量:

string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
Run Code Online (Sandbox Code Playgroud)

输出:

ababababCDabababab
Run Code Online (Sandbox Code Playgroud)

笔记:

where变量实际上是匹配位置的列表,您可以在其中选择第 n 个位置。但是列表项索引0通常以1. 因此有一个n-1索引,n变量是实际的第 n 个子字符串。我的示例找到第 5 个字符串。如果您使用nindex 并想找到第 5 个位置,则需要n4. 您使用的通常取决于函数,它生成我们的n.

这应该是最简单的方式,但也许不是最 Pythonic 的方式,因为where变量构造需要导入re库。也许有人会找到更多 Pythonic 的方式。

来源和一些链接: