我想根据多个字符串的第n次出现添加一个字符串(而不是替换字符串)。
示例:
tablespecs =“ l c d r c l”
现在假设我要在字符串“ here:”中添加l,c和r的第三个外观,所需的输出应为:
desired_tablespecs =“此处的lc:r c l”
因此仅考虑l,c和r,而忽略d。
我只是来得很近,如下所示,代码没有替换匹配项,而是替换了匹配项,因此它提供了“ l c d here: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 here: r c l'
。
略有不同的方法:
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