Suppose this string:
The fox jumped over the log.
Turning into:
I've got a simple method without splitting:
a = "Lorem Ipsum Darum Diesrum!"
while True:
count = a.find(" ")
if count > 0:
a = a.replace(" ", " ")
count = a.find(" ")
continue
else:
break
print(a)
>>> import re
>>> re.sub(' +', ' ', 'The quick brown fox')
'The quick brown fox'
One line of code to remove all extra spaces before, after, and within a sentence:
sentence = " The fox jumped over the log. "
sentence = ' '.join(filter(None,sentence.split(' ')))
Explanation:
*The remaining elements should be words or words with punctuations, etc. I did not test this extensively, but this should be a good starting point. All the best!
foo
is your string:
" ".join(foo.split())
Be warned though this removes "all whitespace characters (space, tab, newline, return, formfeed)" (thanks to hhsaffar, see comments). I.e., "this is \t a test\n"
will effectively end up as "this is a test"
.
This also seems to work:
while " " in s:
s = s.replace(" ", " ")
Where the variable s
represents your string.
If it's whitespace you're dealing with, splitting on None will not include an empty string in the returned value.
5.6.1. String Methods, str.split()