如何在多个指定字符串出现计数后添加字符串

2024-09-30 08:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想添加一个字符串(不替换)的基础上,第n次出现的多个字符串

示例:

tablespecs=“l c d r c l”

现在假设我想在字符串“here:”中添加l、c和r的第三个外观,所需的输出应该是:

所需的\u tablespecs=“l c d here:r c l”

所以只考虑l,c和r,忽略d

我只是像下面一样接近,代码没有添加copde,而是替换匹配项,因此它提供了“lcd here:cll”



tablespecs = "l c d r c l"


def replacenth(string, sub, wanted, n):
    pattern = re.compile(sub)
    where = [m for m in pattern.finditer(string)][n-1]
    before = string[:where.start()]
    after = string[where.end():]
    newString = before + wanted + after

    return newString

#Source of code chunk https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string


replacenth(tablespecs, "[lcr]", "[here:]", 3) 

#wrong_output: 'l c d [here:] c l'

Tags: of字符串in示例stringherewhere基础
2条回答

稍有不同的方法:

tablespecs = "l c d r c l"


def replacenth(string, sub, wanted, n):
    count = 0
    out = ""

    for c in string:
        if c in sub:
            count += 1

        if count == n:
            out += wanted
            count = 0
        out += c
    return out


res = replacenth(tablespecs, "lcr", "here: ", 3)
assert res == "l c d here: r c l", res

您可以将after设置为从where.start()开始,而不是从where.end()开始,以便它包含该字符

tablespecs = "l c d r c l"

def replacenth(string, sub, wanted, n):
    pattern = re.compile(sub)
    where = [m for m in pattern.finditer(string)][n-1]
    before = string[:where.start()]
    after = string[where.start():]
    newString = before + wanted + after
    return newString

replacenth(tablespecs, "[lcr]", "here: ", 3) 

输出'l c d here: r c l'

相关问题 更多 >

    热门问题