我有一个包含数据的字符串,它看起来像这样:
str1 = "[2.4],[5],[2.54],[4],[3.36],[4.46],[3.36],[4],[3.63],[4.86],[4],[4.63]"
我想要用
","
替换每隔一个"],["
的迭代,使其看起来像这样:str2 = "[2.4,5],[2.54,4],[3.36,4.46],[3.36,4],[3.63,4.86],[4,4.63]"
以下是我目前的进展:
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)
我正在尝试玩弄这个东西:
(.*?],\[){2}
但是使用循环似乎没有给我想要的结果。我尝试使用循环,但是我只能替换第二个出现的内容,并且在使用我在这里找到的示例代码后什么都没有改变。 代码如下:here。
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
谢谢。