0

Let's say there is a variable a, and it is declared like this:

a = "Hello  World!"

And I want to make a condition. That is, if the spaces of a is more than 1, then make the spaces of a only one space. The result should be like this:

a = "Hello World!"

With only 1 space rather than two spaces. I could apply it on input purposes as well.

Note: I wish to emphasize on sep for this question.

user19604272
  • 25
  • 1
  • 7
  • There are at least two operations you want to do. You need to know and detect that there are multiple spaces next ot each other (the condition), then you need to replace it with just one space (the operation). You need to do them separately. – aIKid Jul 30 '22 at 02:32
  • 1
    Does this answer your question? [Is there a simple way to remove multiple spaces in a string?](https://stackoverflow.com/questions/1546226/is-there-a-simple-way-to-remove-multiple-spaces-in-a-string) – jkr Jul 30 '22 at 03:14
  • `" ".join(a.split())` is the best you can do, in my opinion (see linked answer in my previous comment) – jkr Jul 30 '22 at 15:20

1 Answers1

1

You can use a regex to replace all instances of multiple consecutive spaces with a single space. For example:

import re

a = "Hello  World!"

a = re.sub(' +', ' ', a)

print(a)
Amit Eyal
  • 459
  • 3
  • 11