我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
我如何剥离所有的空间在一个python字符串?例如,我想要一个像stripmyspaces这样的字符串变成stripmyspaces,但我似乎不能用strip()来完成:
>>> 'strip my spaces'.strip()
'strip my spaces'
当前回答
利用str.split没有sep参数的行为:
>>> 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个选项之间的区别。
其他回答
正如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
利用str.split没有sep参数的行为:
>>> 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个选项之间的区别。
筛选列表的标准技术适用,尽管它们不如拆分/连接或转换方法有效。
我们需要一组空白:
>>> 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
import re
re.sub(' ','','strip my spaces')
对于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空白字符,例如:
插入空格, 他们的空间, 表意的空间,
…等。在“带有White_Space属性的Unicode字符”下面可以看到完整的列表。
但是\s不覆盖不属于空格的字符,这些字符实际上是空格,例如:
任意工匠, 蒙古语元音分隔符, 零宽度不间断空格(又称字节顺序标记),
…等。请在“没有White_Space属性的相关Unicode字符”下面查看完整列表。
所以这6个字符包含在第二个正则表达式的列表中,\u180B|\u200B|\u200C|\u200D|\u2060|\uFEFF。
来源:
https://docs.python.org/2/library/re.html https://docs.python.org/3/library/re.html https://en.wikipedia.org/wiki/Unicode_character_property