0

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Rookie
  • 33
  • 4
  • Do you mean the _literal_ strings `"< SPACE >"` or do you mean actual (white-)spaces, as in `" "`? – Daniil Fajnberg Sep 07 '22 at 20:19
  • I mean actual whitespaces " " – Rookie Sep 07 '22 at 20:21
  • Welcome to Stack Overflow. The code formatting shows spaces, so there is no need or reason to show them like that. I [edit]ed the post to fix that, and also explain the problem more simply and directly. Anyway, please see the linked duplicate. – Karl Knechtel Sep 07 '22 at 20:39

1 Answers1

1

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)
Daniil Fajnberg
  • 12,753
  • 2
  • 10
  • 41