I have a string with data that looks like this:
str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
I would want to replace every second iteration of "],["
with ","
so it will look like this:
str2 = "[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]"
Here is was I have so far:
str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
s2 = re.sub(r"],\[", ',', str1)
print(s2)
I was trying to mess around with this:
(.*?],\[){2}
But it does not seem to yield me the desired results.
I tried using loops but I only managed to replace only the second occurrence and nothing after using this sample code I found here. And the code is:
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)
For these variables:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
Thank you.