Search code examples
pythonpython-re

Python - Add a space every two commas in a string


I have a string of floating number separated by commas:

s: "23.4, 56.8, 23, 67.8, 67.8, 234.6, 68.9, 345.56"

I would like to remove the space after the comma between two numbers forming "pairs" while keeping the other spaces:

new_s: "23.4,56.8, 23,67.8, 67.8,234.6, 68.9,345.56"

Any idea how to do it using python?

I already tried to remove spaces and and use the expression:

import re
s = "23.4, 56.8, 23, 67.8, 67.8, 234.6, 68.9, 345.56"
s = s.replace(" ", "")
new_s = re.sub(r',([^,]*,[^,]*),', r',\1 ', s)
print(new_s)

but it did not work


Solution

  • You could use (,[^,]*,) to match every other comma and the text in between, then replace with the full match followed by a space:

    s = '23.4,56.8,23,67.8,67.8,234.6,68.9,345.56'
    new_s = re.sub(r'(,[^,]*,)', r'\1 ', s)
    

    Output: '23.4,56.8, 23,67.8, 67.8,234.6, 68.9,345.56'

    regex demo