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
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)
每隔五分之一查找一个b,使用count计数b,当我们到达第五个b时,我们重置计数器并继续下一个字符。在
这可能不是最简洁的方法,您可以找到
b
的所有索引,取每个5th
一个,然后分配c
。由于str
中的索引不可赋值,因此必须转换为list。在输出:
^{pr2}$相关问题 更多 >
编程相关推荐