我想添加一个字符串(不替换)的基础上,第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'
稍有不同的方法:
您可以将
after
设置为从where.start()
开始,而不是从where.end()
开始,以便它包含该字符输出
'l c d here: r c l'
相关问题 更多 >
编程相关推荐