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

replace multiple whitespace with single space but keep new lines in regex match (python)

How can I clean up the following text with regex in python? I’m trying to replace multiple whitespaces and tabs with single spaces, but preserve new lines.

test = "This is a test. \n Blah blah."

In my new string, I want it to be:

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

"This is a test. \n Blah blah."

I’ve tried the following expression in an attempt to ignore new line characters, but it doesn’t seem to work.

result = re.sub('[^\n]\s\s+', ' ', test)

Thanks!

>Solution :

You can use code below:

import re
test = "This      is a    test. \n  Blah     blah."
print(re.sub(r"(?:(?!\n)\s)+", " ",test))

Output

This is a test. 
 Blah blah.
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