Pad*_*ham 18
您可以使用while循环str.find
来查找第n个匹配项(如果它存在)并使用该位置创建新字符串:
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
Run Code Online (Sandbox Code Playgroud)
例:
In [14]: s = "foobarfoofoobarbar"
In [15]: nth_repl(s, "bar","replaced",3)
Out[15]: 'foobarfoofoobarreplaced'
In [16]: nth_repl(s, "foo","replaced",3)
Out[16]: 'foobarfooreplacedbarbar'
In [17]: nth_repl(s, "foo","replaced",5)
Out[17]: 'foobarfoofoobarbar'
Run Code Online (Sandbox Code Playgroud)
我使用简单的函数,它列出所有出现的位置,选择第 n 个位置并使用它将原始字符串拆分为两个子字符串。然后它替换第二个子字符串中的第一次出现并将子字符串连接回新字符串:
import re
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted, 1)
newString = before + after
print(newString)
Run Code Online (Sandbox Code Playgroud)
对于这些变量:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
Run Code Online (Sandbox Code Playgroud)
输出:
ababababCDabababab
Run Code Online (Sandbox Code Playgroud)
笔记:
该
where
变量实际上是匹配位置的列表,您可以在其中选择第 n 个位置。但是列表项索引0
通常以1
. 因此有一个n-1
索引,n
变量是实际的第 n 个子字符串。我的示例找到第 5 个字符串。如果您使用n
index 并想找到第 5 个位置,则需要n
是4
. 您使用的通常取决于函数,它生成我们的n
.
这应该是最简单的方式,但也许不是最 Pythonic 的方式,因为
where
变量构造需要导入re
库。也许有人会找到更多 Pythonic 的方式。
来源和一些链接:
归档时间: |
|
查看次数: |
14036 次 |
最近记录: |