假设这个字符串:

The   fox jumped   over    the log.

变成:

The fox jumped over the log.

在不分割和进入列表的情况下,最简单的实现方法(1-2行)是什么?


当前回答

你也可以在Pandas DataFrame中使用字符串分割技术,而不需要使用.apply(..),如果你需要对大量字符串快速执行操作,这是非常有用的。这是一行话:

df['message'] = (df['message'].str.split()).str.join(' ')

其他回答

类似于前面的解决方案,但更具体:用一个空格替换两个或多个空格:

>>> import re
>>> s = "The   fox jumped   over    the log."
>>> re.sub('\s{2,}', ' ', s)
'The fox jumped over the log.'

我尝试过下面的方法,它甚至适用于极端的情况,比如:

str1='          I   live    on    earth           '

' '.join(str1.split())

但如果你更喜欢正则表达式,它可以这样做:

re.sub('\s+', ' ', str1)

尽管必须进行一些预处理以删除尾随和结束空格。

一个简单的灵魂

>>> import re
>>> s="The   fox jumped   over    the log."
>>> print re.sub('\s+',' ', s)
The fox jumped over the log.
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='') 

结果:作为代码

"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" 

你能得到的用户生成字符串的最快速度是:

if '  ' in text:
    while '  ' in text:
        text = text.replace('  ', ' ')

短路使它比pythonlarry的综合回答略快。如果你追求效率,并严格要求去除单个空格的额外空白,那么可以使用这种方法。