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

wro*_*ame 166 python spaces strip python-3.x

如何删除python字符串中的所有空格?例如,我要一个字符串喜欢strip my spaces被变成stripmyspaces,但我似乎无法做到与strip():

>>> 'strip my spaces'.strip()
'strip my spaces'
Run Code Online (Sandbox Code Playgroud)

小智 283

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

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
Run Code Online (Sandbox Code Playgroud)

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

>>> s.replace(" ", "")
'\tfoo\nbar'
Run Code Online (Sandbox Code Playgroud)

过早优化

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

$ 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
Run Code Online (Sandbox Code Playgroud)

请注意,正则表达式是缓存的,因此它并不像您想象的那么慢.编译事前帮助一些,但在实践中,如果你把这个只会重要很多倍:

$ 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
Run Code Online (Sandbox Code Playgroud)

即使re.sub慢了11.3倍,记住你的瓶颈肯定在其他地方.大多数程序都不会注意到这三种选择中的任何一种.

  • @OTZ:您可能会感到惊讶,但请参阅“记住”注释。 (2认同)
  • 我不知道 .split() 会捕获任何类型的空白,我敢打赌下一个人阅读我的代码也不会知道这一点(这包括六个月后的我未来的自己)。 (2认同)

Tim*_*tes 54

>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'
Run Code Online (Sandbox Code Playgroud)

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

  • 与接受的答案相比,这比解决方案的难度小得多。 (2认同)
  • 这比其他答案更明确,所以它对我来说很重要。 (2认同)

Dan*_*nes 28

或者,

"strip my spaces".translate( None, string.whitespace )
Run Code Online (Sandbox Code Playgroud)

这是Python3版本:

"strip my spaces".translate(str.maketrans('', '', string.whitespace))
Run Code Online (Sandbox Code Playgroud)

  • `NameError:未定义名称'string'。 (3认同)
  • @ZelphirKaltstahl 你需要“导入字符串” (3认同)

car*_*arl 12

最简单的是使用替换:

"foo bar\t".replace(" ", "").replace("\t", "")
Run Code Online (Sandbox Code Playgroud)

或者,使用正则表达式:

import re
re.sub(r"\s", "", "foo bar\t")
Run Code Online (Sandbox Code Playgroud)

  • `\ s +`更好. (4认同)

小智 5

在Python中删除起始空间

string1="    This is Test String to strip leading space"
print string1
print string1.lstrip()
Run Code Online (Sandbox Code Playgroud)

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

string2="This is Test String to strip trailing space     "
print string2
print string2.rstrip()
Run Code Online (Sandbox Code Playgroud)

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

string3="    This is Test String to strip leading and trailing space      "
print string3
print string3.strip()
Run Code Online (Sandbox Code Playgroud)

删除python中的所有空格

string4="   This is Test String to test all the spaces        "
print string4
print string4.replace(" ", "")
Run Code Online (Sandbox Code Playgroud)