我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
当前回答
删除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(" ", ""))
其他回答
另外,
"strip my spaces".translate( None, string.whitespace )
下面是Python3版本:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
下面是另一种使用普通列表理解的方法:
''.join([c for c in aString if c not in [' ','\t','\n']])
例子:
>>> aStr = 'aaa\nbbb\t\t\tccc '
>>> print(aString)
aaa
bbb ccc
>>> ''.join([c for c in aString if c not in [' ','\t','\n']])
'aaabbbccc'
删除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(" ", ""))
import re
re.sub(' ','','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