Suppose this string:
The fox jumped over the log.
Turning into:
The fox jumped over the log.
What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?
Suppose this string:
The fox jumped over the log.
Turning into:
The fox jumped over the log.
What is the simplest (1-2 lines) to achieve this, without splitting and going into lists?
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.
import re
Text = " You can select below trims for removing white space!! BR Aliakbar "
# trims all white spaces
print('Remove all space:',re.sub(r"\s+", "", Text), sep='')
# trims left space
print('Remove leading space:', re.sub(r"^\s+", "", Text), sep='')
# trims right space
print('Remove trailing spaces:', re.sub(r"\s+$", "", Text), sep='')
# trims both
print('Remove leading and trailing spaces:', re.sub(r"^\s+|\s+$", "", Text), sep='')
# replace more than one white space in the string with one white space
print('Remove more than one space:',re.sub(' +', ' ',Text), sep='')
Result: as code
"Remove all space:Youcanselectbelowtrimsforremovingwhitespace!!BRAliakbar"
"Remove leading space:You can select below trims for removing white space!! BR Aliakbar"
"Remove trailing spaces: You can select below trims for removing white space!! BR Aliakbar"
"Remove leading and trailing spaces:You can select below trims for removing white space!! BR Aliakbar"
"Remove more than one space: You can select below trims for removing white space!! BR Aliakbar"
You can also use the string splitting technique in a Pandas DataFrame without needing to use .apply(..), which is useful if you need to perform the operation quickly on a large number of strings. Here it is on one line:
df['message'] = (df['message'].str.split()).str.join(' ')
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
" ".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.
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
Because @pythonlarry asked here are the missing generator based versions
The groupby join is easy. Groupby will group elements consecutive with same key. And return pairs of keys and list of elements for each group. So when the key is an space an space is returne else the entire group.
from itertools import groupby
def group_join(string):
return ''.join(' ' if chr==' ' else ''.join(times) for chr,times in groupby(string))
The group by variant is simple but very slow. So now for the generator variant. Here we consume an iterator, the string, and yield all chars except chars that follow an char.
def generator_join_generator(string):
last=False
for c in string:
if c==' ':
if not last:
last=True
yield ' '
else:
last=False
yield c
def generator_join(string):
return ''.join(generator_join_generator(string))
So i meassured the timings with some other lorem ipsum.
With Hello and World separated by 64KB of spaces
Not forget the original sentence
Interesting here for nearly space only strings group join is not that worse Timing showing always median from seven runs of a thousand times each.
This one does exactly what you want
old_string = 'The fox jumped over the log '
new_string = " ".join(old_string.split())
print(new_string)
Will results to
The fox jumped over the log.
This does and will do: :)
# python... 3.x
import operator
...
# line: line of text
return " ".join(filter(lambda a: operator.is_not(a, ""), line.strip().split(" ")))