wro*_*ame 166 python spaces strip python-3.x
如何删除python字符串中的所有空格?例如,我要一个字符串喜欢strip my spaces被变成stripmyspaces,但我似乎无法做到与strip():
>>> 'strip my spaces'.strip()
'strip my spaces'
Run Code Online (Sandbox Code Playgroud)
小智 283
利用没有sep参数的str.split行为:
>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
Run Code Online (Sandbox Code Playgroud)
如果您只想删除空格而不是所有空格:
>>> s.replace(" ", "")
'\tfoo\nbar'
Run Code Online (Sandbox Code Playgroud)
即使效率不是主要目标 - 编写明确的代码 - 这里是一些初始时间:
$ 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
Run Code Online (Sandbox Code Playgroud)
请注意,正则表达式是缓存的,因此它并不像您想象的那么慢.编译事前帮助一些,但在实践中,如果你把这个只会重要很多倍:
$ 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
Run Code Online (Sandbox Code Playgroud)
即使re.sub慢了11.3倍,记住你的瓶颈肯定在其他地方.大多数程序都不会注意到这三种选择中的任何一种.
Tim*_*tes 54
>>> import re
>>> re.sub(r'\s+', '', 'strip my spaces')
'stripmyspaces'
Run Code Online (Sandbox Code Playgroud)
还处理你没想到的任何空白字符(相信我,有很多).
Dan*_*nes 28
或者,
"strip my spaces".translate( None, string.whitespace )
Run Code Online (Sandbox Code Playgroud)
这是Python3版本:
"strip my spaces".translate(str.maketrans('', '', string.whitespace))
Run Code Online (Sandbox Code Playgroud)
car*_*arl 12
最简单的是使用替换:
"foo bar\t".replace(" ", "").replace("\t", "")
Run Code Online (Sandbox Code Playgroud)
或者,使用正则表达式:
import re
re.sub(r"\s", "", "foo bar\t")
Run Code Online (Sandbox Code Playgroud)
小智 5
string1=" This is Test String to strip leading space"
print string1
print string1.lstrip()
Run Code Online (Sandbox Code Playgroud)
string2="This is Test String to strip trailing space "
print string2
print string2.rstrip()
Run Code Online (Sandbox Code Playgroud)
string3=" This is Test String to strip leading and trailing space "
print string3
print string3.strip()
Run Code Online (Sandbox Code Playgroud)
string4=" This is Test String to test all the spaces "
print string4
print string4.replace(" ", "")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
246202 次 |
| 最近记录: |