Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading