如何从字符串中去除所有空格 [英] How to strip all whitespace from string
问题描述
如何去除 python 字符串中的所有空格?例如,我希望将像 strip my Spaces
这样的字符串转换为 stripmyspaces
,但我似乎无法使用 strip()
来实现:
利用 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 个循环,最好的 3 个:每个循环 1.38 微秒$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'100000 个循环,最好的 3 个:每个循环 15.6 微秒
请注意,正则表达式已被缓存,因此它并不像您想象的那么慢.事先编译它会有所帮助,但只有在您多次调用它时才会在实践中重要:
$ python -m timeit -s 'import re;e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'100000 个循环,最好的 3 个:每个循环 7.76 微秒
尽管 re.sub 慢了 11.3 倍,但请记住,您的瓶颈肯定在其他地方.大多数程序不会注意到这 3 个选项中的任何一个之间的区别.
How do I strip all the spaces in a python string? For example, I want a string like strip my spaces
to be turned into stripmyspaces
, but I cannot seem to accomplish that with strip()
:
>>> 'strip my spaces'.strip()
'strip my spaces'
Taking advantage of str.split's behavior with no sep parameter:
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
If you just want to remove spaces instead of all whitespace:
>>> s.replace(" ", "")
'\tfoo\nbar'
Premature optimization
Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:
$ 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
Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:
$ 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
Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.
这篇关于如何从字符串中去除所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!