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

2024-10-04 01:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我打算把五分之一的“b”换成“c” 这是我的输入字符串:

jStr = aabbbbbaa

这是密码

^{pr2}$

我得到的结果是一样的

aabbbbbaa

我是从什么开始的?在


Tags: 字符串密码pr2jstraabbbbbaa
2条回答
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

每隔五分之一查找一个b,使用count计数b,当我们到达第五个b时,我们重置计数器并继续下一个字符。在

这可能不是最简洁的方法,您可以找到b的所有索引,取每个5th一个,然后分配c。由于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)

输出:

^{pr2}$

相关问题 更多 >