我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:

>>> 'strip my spaces'.strip()
'strip my spaces'

当前回答

筛选列表的标准技术适用,尽管它们不如拆分/连接或转换方法有效。

我们需要一组空白:

>>> import string
>>> ws = set(string.whitespace)

内置过滤器:

>>> "".join(filter(lambda c: c not in ws, "strip my spaces"))
'stripmyspaces'

一个列表推导式(是的,使用括号:参见下面的基准测试):

>>> import string
>>> "".join([c for c in "strip my spaces" if c not in ws])
'stripmyspaces'

折叠:

>>> import functools
>>> "".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))
'stripmyspaces'

基准:

>>> from timeit import timeit
>>> timeit('"".join("strip my spaces".split())')
0.17734256500003198
>>> timeit('"strip my spaces".translate(ws_dict)', 'import string; ws_dict = {ord(ws):None for ws in string.whitespace}')
0.457635745999994
>>> timeit('re.sub(r"\s+", "", "strip my spaces")', 'import re')
1.017787621000025

>>> SETUP = 'import string, operator, functools, itertools; ws = set(string.whitespace)'
>>> timeit('"".join([c for c in "strip my spaces" if c not in ws])', SETUP)
0.6484303600000203
>>> timeit('"".join(c for c in "strip my spaces" if c not in ws)', SETUP)
0.950212219999969
>>> timeit('"".join(filter(lambda c: c not in ws, "strip my spaces"))', SETUP)
1.3164566040000523
>>> timeit('"".join(functools.reduce(lambda acc, c: acc if c in ws else acc+c, "strip my spaces"))', SETUP)
1.6947649049999995

其他回答

另外,

"strip my spaces".translate( None, string.whitespace )

下面是Python3版本:

"strip my spaces".translate(str.maketrans('', '', string.whitespace))

正如Roger Pate所提到的,以下代码对我来说是有效的:

s = " \t foo \n bar "
"".join(s.split())
'foobar'

我正在使用Jupyter Notebook运行以下代码:

i=0
ProductList=[]
while i < len(new_list): 
   temp=''                            # new_list[i]=temp=' Plain   Utthapam  '
   #temp=new_list[i].strip()          #if we want o/p as: 'Plain Utthapam'
   temp="".join(new_list[i].split())  #o/p: 'PlainUtthapam' 
   temp=temp.upper()                  #o/p:'PLAINUTTHAPAM' 
   ProductList.append(temp)
   i=i+2

这个问题在面试中被问到。如果你要用条形法来解的话。这是一种方法

s='string with spaces'
res=''.join((i.strip(' ') for i in s))
print(res)

将字符串分成单词 去掉两边的空白 最后用单一的空间将它们连接起来

代码的最后一行:

' '.join(word.strip() for word in message_text.split()

如果不需要最佳性能,你只想要一些非常简单的东西,你可以定义一个基本函数来测试每个字符,使用string类内置的"isspace"方法:

def remove_space(input_string):
    no_white_space = ''
    for c in input_string:
        if not c.isspace():
            no_white_space += c
    return no_white_space

以这种方式构建no_white_space字符串不会有理想的性能,但解决方案很容易理解。

>>> remove_space('strip my spaces')
'stripmyspaces'

如果不想定义函数,可以将其转换为与列表推导式略有相似的内容。借用顶部答案的连接解决方案:

>>> "".join([c for c in "strip my spaces" if not c.isspace()])
'stripmyspaces'