我想要从一个字符串中去除所有的空格。
" as fa sdf sdfsdf "
结果应为:
"asfasdfsdfsdf"
有几种方法可以实现这个目标,我在思考哪一种是最好的。
1.
"".join(" as fa sdf sdfsdf ".split())
2.
" as fa sdf sdfsdf ".replace(" ", "")
我假设还有更多的选择。
哪一个更受欢迎?
我想要从一个字符串中去除所有的空格。
" as fa sdf sdfsdf "
结果应为:
"asfasdfsdfsdf"
有几种方法可以实现这个目标,我在思考哪一种是最好的。
1.
"".join(" as fa sdf sdfsdf ".split())
2.
" as fa sdf sdfsdf ".replace(" ", "")
我假设还有更多的选择。
哪一个更受欢迎?
我认为最好、最有效的方法是第二个版本:" as fa sdf sdfsdf ".replace(" ", "")
,你可以使用timeit
模块作为证据:
python -m timeit '"".join(" as fa sdf sdfsdf ".split())'
1000000 次循环中,最优秀的 3 次结果:每次循环耗时 0.554 微秒
python -m timeit '" as fa sdf sdfsdf ".replace(" ", "")'
1000000 次循环中,最优秀的 3 次结果:每次循环耗时 0.405 微秒
replace(" ", "")
是最清晰和最简洁的。
使用此方法可以一次性删除所有空格:
import re
s = ' as fa sdf sdfsdf '
s = re.sub(r'\s+', '', s)
s
=> 'asfasdfsdfsdf'
r'\s+'
匹配“一个或多个”空白字符——包括空格、制表符等。使用 replace
方法不能移除所有空格字符(例如换行符,制表符):
>>> 'abc\t\ndef'.replace(" ", "")
'abc\t\ndef'
string.translate
:>>> import string
>>> 'abc\t\ndef'.translate(None, string.whitespace)
'abcdef'
编辑:对于Unicode字符串,string.translate
不起作用;您可能希望使用 re.sub('\s', '', 'abc\n\tdef')
代替。
string.translate
在Python 3中无法与Unicode字符串一起使用(或根本无法用于删除)。 - Samuel Isaacson'abc\t\ndef'.translate(str.maketrans('','',string.whitespace))
。字典键必须是Unicode序数值(整数),而不是字符。 - Mark Tolonen正则表达式
>>> str = " as fa sdf sdfsdf "
>>> import re
>>> re.sub(r'\s', '', str)
再加入一个:
from string import whitespace
ws = set(whitespace)
''.join(ch for ch in my_string if ch not in ws)
''.join(ch for ch in my_string if not ch.isspace())
- Steven Rumbalskire.sub(" ","", s)
是我最喜欢的。
正则表达式很简单,而且它很有效。 split()
稍微有点复杂。相比之下,正则表达式更受欢迎。