简体   繁体   English

如何替换字符串中子字符串/字符的第n次出现? [Python 3]

[英]How can I replace the nth occurence of a substring/character within a string? [Python 3]

I was going for replacing every fifth "b" with "c" Here is my input string: 我打算用“ c”替换每五个“ b”,这是我的输入字符串:

jStr = aabbbbbaa

Now here is the code 现在这是代码

import re
m = re.search('c', jStr)
jStr1 = jStr[:m.end()]
jStr2 = jStr[:m.end()]
jStr3 = jStr[:m.end()]
jStr4 = jStr[:m.end()]
jStr5 = jStr[m.end():]
jStr6 = jStr5.replace('c', 'b', 1)
jStr == (jStr1+jStr6)

the output I keep getting is the same 我不断得到的输出是相同的

aabbbbbaa

I started with? 我开始了吗?

This might not be the most concise way, you can find all the indices of b , take every 5th one, and then assign c . 这可能不是最简洁的方法,您可以找到b所有索引,取5th个索引,然后分配c Since indices inside str are not assignable, you have to convert to list. 由于str内部的索引不可分配,因此您必须转换为list。

jStr = 'aabbbbbaa'
jStr = list(jStr)

bPos = [x for x in range(len(jStr)) if jStr[x] == 'b']

for i,x in enumerate(bPos):
   if (i+1) % 5 == 0:
      jStr[x] = 'c'

jStr = ''.join(jStr)
print(jStr)

Output: 输出:

aabbbbcaa
jStr = "aabbbbbaabbbbb"
count = 1
res= "" # strings are immutable so we have to create a new string.
for s in jStr:
    if count == 5 and s == "b": # if count is 5 we have our fifth "b", change to "c" and reset count
        res +=  "c"
        count = 1
    elif s == "b": # if it is a "b" but not the fifth just add b to res and increase count
        count += 1
        res += "b"
    else:           # else it is not a "b", just add to res
        res += s 
print(res)
aabbbbcaabbbbc

Finds every fifth b, counting the b's using count, when we have reached the fifth we reset the counter and go on to the next character. 查找每五分之一的b,计算b的使用计数,当我们到达第五位时,我们重置计数器并继续到下一个字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM