Remove multiple whitespaces by single space in a python list

Question:

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"]?

Asked By: Rookie

||

Answers:

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)
Answered By: Daniil Fajnberg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.