如何从字符串中删除所有空格

时间:2010-09-18 00:42:10

标签: python python-3.x spaces strip

如何删除python字符串中的所有空格?例如,我希望将strip my spaces之类的字符串转换为stripmyspaces,但我似乎无法用strip()完成此操作:

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

11 个答案:

答案 0 :(得分:263)

利用没有sep参数的str.split行为:

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

如果您只想删除空格而不是所有空格:

>>> s.replace(" ", "")
'\tfoo\nbar'

过早优化

即使效率不是主要目标 - 编写明确的代码 - 这是一些初始时间:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

注意正则表达式是缓存的,所以它并不像你想象的那么慢。事先编译它会有所帮助,但只有在实践中如果你多次调用许多时才会这样做:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

尽管re.sub慢了11.3倍,但请记住你的瓶颈肯定在其他地方。大多数程序都没有注意到这3种选择中的任何一种。

答案 1 :(得分:49)

>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'

还处理你没想到的任何空格字符(相信我,有很多)。

答案 2 :(得分:27)

可替换地,

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

这是Python3版本:

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

答案 3 :(得分:12)

最简单的方法是使用replace:

"foo bar\t".replace(" ", "").replace("\t", "")

或者,使用正则表达式:

import re
re.sub(r"\s", "", "foo bar\t")

答案 4 :(得分:4)

在Python中删除起始空间

string1="    This is Test String to strip leading space"
print string1
print string1.lstrip()

在Python中删除尾随空格或结尾空间

string2="This is Test String to strip trailing space     "
print string2
print string2.rstrip()

从Python字符串的开头和结尾删除空格

string3="    This is Test String to strip leading and trailing space      "
print string3
print string3.strip()

删除python中的所有空格

string4="   This is Test String to test all the spaces        "
print string4
print string4.replace(" ", "")

答案 5 :(得分:3)

尝试使用re.sub的正则表达式。您可以搜索所有空格并替换为空字符串。

模式中的

\s将匹配空白字符 - 而不仅仅是空格(制表符,换行符等)。您可以阅读更多相关信息in the manual

答案 6 :(得分:3)

import re
re.sub(' ','','strip my spaces')

答案 7 :(得分:2)

如罗杰·佩特(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

答案 8 :(得分:0)

TL / DR

此解决方案已使用Python 3.6进行了测试

要在Python3中从字符串中去除所有空格,可以使用以下函数:

def remove_spaces(in_string: str):
    return in_string.translate(str.maketrans({' ': ''})

要删除任何空白字符('\ t \ n \ r \ x0b \ x0c'),可以使用以下功能:

import string
def remove_whitespace(in_string: str):
    return in_string.translate(str.maketrans(dict.fromkeys(string.whitespace)))

说明

Python的str.translate方法是str的内置类方法,它获取一个表并返回字符串的副本,其中每个字符都通过传递的转换表进行映射。 Full documentation for str.translate

要创建翻译表,请使用str.maketrans。此方法是str的另一个内置类方法。在这里,我们仅将其与一个参数一起使用,在本例中为字典,其中的键是要替换的字符,映射到具有字符替换值的值。它返回一个转换表以与str.translate一起使用。 Full documentation for str.maketrans

python中的string模块包含一些常见的字符串操作和常量。 string.whitespace是一个常量,它返回一个字符串,其中包含所有被视为空格的ASCII字符。其中包括字符空格,制表符,换行符,返回符,换页符和垂直制表符。Full documentation for string

在第二个功能中,dict.fromkeys用于创建字典,其中键是string.whitespace返回的字符串中的字符,每个字符的值为NoneFull documentation for dict.fromkeys

答案 9 :(得分:0)

尽管不如split/jointranslate方法那样有效,但仍可以使用过滤列表的标准技术。

我们需要一组空格:

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

内置的filter

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

答案 10 :(得分:0)

如果不是最佳性能的要求,并且您只想简单地做一些事情,则可以使用字符串类的内置“ 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解决方案中借用:

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