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

Remove multiple whitespaces by single space in a python list

In Python, I have a list like ["HELLO MR GOOD SOUL"]. How can I replace multiple spaces with a single space, to get ["HELLO MR GOOD SOUL"]?

>Solution :

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

You can use re.sub with a regular expression for this:

s = "HELLO     MR      GOOD    SOUL"
re.sub(r"\s+", " ", s)

\s is whitespace, + means one or more. Since Regex is greedy by default, the pattern \s+ will match as many consecutive spaces as possible.

The output:

'HELLO MR GOOD SOUL'

If you actually have a list of strings, you can do a simple list comprehension:

list_of_strings = [...]
[re.sub(r"\s+", " ", s) for s in list_of_strings]

If you want to do it in-place:

for idx, s in enumerate(list_of_strings):
    list_of_strings[idx] = re.sub(r"\s+", " ", s)
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