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


i going replacing every fifth "b" "c" here input string:

jstr = aabbbbbaa 

now here 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 keep getting same

aabbbbbaa 

i started with?

jstr = "aabbbbbaabbbbb" count = 1 res= "" # strings immutable have create new string. s in jstr:     if count == 5 , s == "b": # if count 5 have our fifth "b", change "c" , reset count         res +=  "c"         count = 1     elif s == "b": # if "b" not fifth add b res , increase count         count += 1         res += "b"     else:           # else not "b", add res         res += s  print(res) aabbbbcaabbbbc 

finds every fifth b, counting b's using count, when have reached fifth reset counter , go on next character.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -