'Replace the ',' (comma) with a ' ' (space) after every nth element of a list and write it to a text file in python

I have the following question. bbox2 is a list of data points, and as you see every bbox2[k - 1::k] element is 0.

save_text = [image_path]
bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
bbox2 = str(bbox2).replace(' ', '')
save_text.append(bbox2)
with open('output.txt', 'a') as file:
               file.write(' '.join(map(str, save_text)).replace('[', '').replace(']', '') + '\n')

Now please look at the output. The output I am getting is:

output:
DSC07368_053.jpg 126,0,178,38,0,254,415,316,472,0,390,292,423,326,0

So now my question is how can I write this text file like the expected output.

Expected output:
DSC07368_053.jpg 126,0,178,38,0 254,415,316,472,0 390,292,423,326,0

If I use another .replace(',0,',',0 ') then there is a problem because it is replacing all of it but I need the space after each bbox2[k - 1::k] element instead of a comma.



Solution 1:[1]

Following is the code :

save_text = ["FileName"]
bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
bbox2 = str(bbox2).replace(' ', '')
bbox2 = bbox2.replace('[','').replace(']','')
print(bbox2)

count = 0
IndexOfEveryFifthComma = []
Commas = []
for each in bbox2:

    count = count + 1
    if each == ',':
       Commas.append(each)
       if len(Commas) % 5 == 0:
            IndexOfEveryFifthComma.append(count-1)

print(Commas)
print(IndexOfEveryFifthComma)

bbox2_list = list(bbox2)

for each in IndexOfEveryFifthComma:
    bbox2_list[each] = ' '

bbox2 = ''.join(bbox2_list)
print(bbox2)

save_text.append(bbox2)
with open('output.txt', 'a') as file:
              file.write(' '.join(map(str, save_text)).replace('[', '').replace(']', '') + '\n')

Solution 2:[2]

bbox2 = [126,0,178,38,0,254,415,316,472,0,390,292,423,326,0]
k = 5
output = ""
for index,item in enumerate(bbox2):
    if index % k == 0:
        output += " "
    else:
        output += ","
    output += str(item)
output = output.strip()
print(output)

Output:

126,0,178,38,0 254,415,316,472,0 390,292,423,326,0

Solution 3:[3]

Thanks a lot for all the awesome solutions, I also come with my own solution and it is working fine. I will try the solutions given in this thread: Below was my solution:

def replace_comma(bbox2, image_path):
    start = 0
    text = ""
    for idx in range(len(bbox2) + 1):
        if idx % 5 == 0 and idx != 0:
            next = idx
            val = str(bbox2[start:next]).replace(" ", "")
            text = f"{text} {val}"
            start = next

    text = text.replace("[", "").replace("]", "").strip()
    save_text = f"{image_path} {text}\n"
    return save_text

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Anonymous_Beast
Solution 2 Leo Eiji
Solution 3