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
Active
Viewed 880 times
0

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 Answers
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
-
I did try : list_of_strings = [...] [re.sub(r"\s+", " ", s) for s in list_of_strings] print(list_of_strings) But when I print, it prints the original list and not the modified list – Rookie Sep 07 '22 at 20:33
-
@Rookie well, the list comprehension creates a new list. You need to assign it to a variable. – Daniil Fajnberg Sep 07 '22 at 20:37
-
-
You can just reassign `list_of_strings` to the new list if you don't need to modify the actual object. Or you can assign to the `[:]` slice of that list. Or you can use an explicit `for` loop with `enumerate`. – Karl Knechtel Sep 07 '22 at 20:44
-
-