Suppose this string:
The fox jumped over the log.
Turning into:
I have tried the following method and it even works with the extreme case like:
str1=' I live on earth '
' '.join(str1.split())
But if you prefer a regular expression it can be done as:
re.sub('\s+', ' ', str1)
Although some preprocessing has to be done in order to remove the trailing and ending space.
sentence = "The fox jumped over the log."
word = sentence.split()
result = ""
for string in word:
result += string+" "
print(result)
Solution for Python developers:
import re
text1 = 'Python Exercises Are Challenging Exercises'
print("Original string: ", text1)
print("Without extra spaces: ", re.sub(' +', ' ', text1))
Output:
Original string: Python Exercises Are Challenging Exercises
Without extra spaces: Python Exercises Are Challenging Exercises
Quite surprising - no one posted simple function which will be much faster than ALL other posted solutions. Here it goes:
def compactSpaces(s):
os = ""
for c in s:
if c != " " or (os and os[-1] != " "):
os += c
return os
Another alternative:
>>> import re
>>> str = 'this is a string with multiple spaces and tabs'
>>> str = re.sub('[ \t]+' , ' ', str)
>>> print str
this is a string with multiple spaces and tabs
" ".join(foo.split())
is not quite correct with respect to the question asked because it also entirely removes single leading and/or trailing white spaces. So, if they shall also be replaced by 1 blank, you should do something like the following:
" ".join(('*' + foo + '*').split()) [1:-1]
Of course, it's less elegant.