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 :

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:


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)

Leave a Reply