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

How to replace spaces between words using regex?

I am trying to convert a string of words and numbers into a list, every item is separated with a space, so using .replace(" ", ",").split(",") would be an easy solution, but unfortunately, sometimes there are multiple words in the object name, and I would like these words to be connected with a _

Example:

office supplies 674.56 570.980487 755.84 682.360029

Expected output:

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

office_supplies 674.56 570.980487 755.84 682.360029

I have found this:
Replace spaces between letters only

And tried to implement it like this:

sample_line = "office supplies 674.56 570.980487 755.84 682.360029"
regex = re.compile(':%s/\v(\a)\s(\a)/\1_\2/g', re.I)
print(re.sub(p, r"\1\2", line))

But it does not seem to replace the spaces, I am not very sharp with regex, but according to the linked issue, it should work.

>Solution :

You may probably use this re.sub + split solution:

import re
s = 'office supplies 674.56 570.980487 755.84 682.360029'
print ( re.sub(r'(?<=[a-zA-Z])\s+(?=[a-zA-Z])', '_', s).split() )

Output:

['office_supplies', '674.56', '570.980487', '755.84', '682.360029']

Here:

  • Regex (?<=[a-zA-Z])\s+(?=[a-zA-Z]) matches 1+ whitespace surrounded with letters only
  • split will split string on whitespaces
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