【发布时间】:2018-03-24 03:38:12
【问题描述】:
我从问题Replace nth occurrence of substring in string 中提取了以下sn-p。
这将替换第 n 个子字符串的单个出现。但是我想在每个第 n 个子字符串中替换所有出现
所以如果字符串中出现 30 次子字符串,例如,我想替换整个 10 和 20,但我根本不知道如何实现这一点
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
【问题讨论】:
-
'every nth' 立即让人想起模数运算符
%,其中有一个递增循环,每次通过检查incrementor % n,如果为零,则进行更改
标签: python