219

如何去除python字符串中的所有空格?例如,我想将一个字符串strip my spaces变成stripmyspaces,但我似乎无法通过以下方式实现strip()

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

12 回答 12

374

在没有 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 倍,但请记住,您的瓶颈肯定在其他地方。大多数程序不会注意到这三个选项之间的区别。

于 2010-09-18T00:54:26.467 回答
79

对于 Python 3:

>>> import re
>>> re.sub(r'\s+', '', 'strip my \n\t\r ASCII and \u00A0 \u2003 Unicode spaces')
'stripmyASCIIandUnicodespaces'
>>> # Or, depending on the situation:
>>> re.sub(r'(\s|\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF)+', '', \
... '\uFEFF\t\t\t strip all \u000A kinds of \u200B whitespace \n')
'stripallkindsofwhitespace'

...处理您没有想到的任何空白字符 - 相信我们,有很多。

\s其本身总是涵盖 ASCII 空白:

  • (常规)空间
  • 标签
  • 新行 (\n)
  • 回车 (\r)
  • 换页
  • 垂直制表符

此外:

  • 对于re.UNICODE启用的 Python 2,
  • 对于没有任何额外操作的 Python 3,

...\s还涵盖了 Unicode 空白字符,例如:

  • 不间断的空间,
  • em空间,
  • 表意空间,

...ETC。请参阅此处的完整列表,在“具有 White_Space 属性的 Unicode 字符”下

但是\s,不包括未被归类为空格的字符,这些字符实际上是空格,例如:

  • 零宽度连接器,
  • 蒙古语元音分隔符,
  • 零宽度不间断空间(又名字节顺序标记),

...ETC。请参阅此处的完整列表,在“没有 White_Space 属性的相关 Unicode 字符”下

所以这 6 个字符被第二个正则表达式中的列表覆盖,\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF.

资料来源:

于 2010-09-18T00:48:21.257 回答
36

或者,

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

这是 Python3 版本:

"strip my spaces".translate(str.maketrans('', '', string.whitespace))
于 2013-05-20T16:16:31.477 回答
14

最简单的是使用替换:

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

或者,使用正则表达式:

import re
re.sub(r"\s", "", "foo bar\t")
于 2010-09-18T00:48:15.147 回答
13

删除 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(" ", ""))
于 2018-11-20T19:56:38.017 回答
3

正如 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
于 2018-06-27T07:18:54.240 回答
2

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

\s在您的模式中将匹配空白字符 - 而不仅仅是空格(制表符、换行符等)。您可以在手册中阅读有关它的更多信息。

于 2010-09-18T00:46:52.257 回答
2

过滤列表的标准技术适用,尽管它们不如split/joinortranslate方法有效。

我们需要一组空格:

>>> 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
于 2019-04-04T19:12:14.850 回答
2
import re
re.sub(' ','','strip my spaces')
于 2016-10-24T13:14:42.550 回答
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 的内置类方法,它接受一个表并返回字符串的副本,其中每个字符都通过传递的转换表映射。str.translate 的完整文档

用于创建转换表str.maketrans。这个方法是另一个内置的类方法str。这里我们只使用一个参数,在本例中是一个字典,其中键是要替换的字符,映射到具有字符替换值的值。它返回一个转换表以用于str.translate. str.maketrans 的完整文档

stringpython中的模块包含一些常见的字符串操作和常量。string.whitespace是一个常量,它返回一个字符串,其中包含所有被视为空白的 ASCII 字符。这包括字符空格、制表符、换行符、回车符、换页符和垂直制表符。字符串的完整文档

在第二个函数dict.fromkeys中,用于创建一个字典,其中键是每个返回的字符串中的字符string.whitespacevalue Nonedict.fromkeys 的完整文档

于 2019-03-27T16:51:42.643 回答
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'
于 2019-11-08T22:15:22.870 回答
0
  1. 你的字符串分割成单独的单词
  2. 去除两边的空白
  3. 最后用单个空格加入它们

最后一行代码:

' '.join(word.strip() for word in message_text.split()
于 2021-10-17T11:28:40.570 回答