gpt4 book ai didi

python - 如何在计算多个特定字符串的出现次数后添加字符串

转载 作者:行者123 更新时间:2023-12-01 00:25:08 25 4
gpt4 key购买 nike

我想根据多个字符串的第 n 次出现添加一个字符串(而不是替换)。

示例:

tablespecs =“lc d r c l”

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

desired_tablespecs = "l c d 此处:r c l"

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

我只是很接近,如下所示,代码没有添加 copde,而是替换了匹配项,因此它在此处传递“l c d: c l”。



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'

最佳答案

您可以将 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:r c l'

关于python - 如何在计算多个特定字符串的出现次数后添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58642831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com