我该如何在Python字符串中删除所有空格?例如,我想将像strip my spaces
这样的字符串转换为stripmyspaces
,但似乎无法使用strip()
实现:
>>> 'strip my spaces'.strip()
'strip my spaces'
我该如何在Python字符串中删除所有空格?例如,我想将像strip my spaces
这样的字符串转换为stripmyspaces
,但似乎无法使用strip()
实现:
>>> 'strip my spaces'.strip()
'strip my spaces'
>>> 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 操作较慢,但请记住你的程序瓶颈肯定出现在其他地方。大多数程序不会注意到这 3 种选择之间的差异。
None
。但令人惊讶的是,这样会使速度变慢... - martineaumyString.translate(None, " \t\r\n\v")
。它只需要 Roger 最快的(分割和连接)技术的 83% 的时间。不确定它是否涵盖了所有分割所做的所有空格字符,但对于大多数 ASCII 应用程序来说,它可能已经足够了。 - brianmearns对于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空白字符,包括:
此外:
re.UNICODE
的Python 2,\s
也可以匹配Unicode空格字符,例如:
完整列表请参见这里,"Unicode characters with White_Space property"部分。
然而,\s
不能匹配那些虽然实际上是空格但却未被分类为空格的字符,例如:
完整列表请参见这里,"Related Unicode characters without White_Space property"部分。
因此,这6个字符被包含在第二个正则表达式的列表中:\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF
。
参考资料:
\s
在许多情况下对于 Unicode 字符串而言已经足够,不仅仅是 ASCII)。它强调了 Python 2(现在已经停止支持),并增加了复杂性。我认为简要提到 Python 2 并解释其差异就足以选择正确的方法了。 - Tim Yates或者,
"strip my spaces".translate( None, string.whitespace )
以下是Python3版本:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
string
模块。 - Shahryar Saljoughistring1 = " This is Test String to strip leading space"
print(string1)
print(string1.lstrip())
string2 = "This is Test String to strip trailing space "
print(string2)
print(string2.rstrip())
string3 = " This is Test String to strip leading and trailing space "
print(string3)
print(string3.strip())
string4 = " This is Test String to test all the spaces "
print(string4)
print(string4.replace(" ", ""))
"foo bar\t".replace(" ", "").replace("\t", "")
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")
正如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
import re
re.sub(' ','','strip my spaces')
标准的过滤列表技术可以应用,但它们不如 split/join
或 translate
方法高效。
我们需要一组空格:
>>> 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
最终代码行:
' '.join(word.strip() for word in message_text.split()