我想删除字符串中的任何括号.为什么这不能正常工作?
>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington
Run Code Online (Sandbox Code Playgroud)
bob*_*nce 80
因为那不是什么strip().它删除参数中存在的前导和尾随字符,但不删除字符串中间的那些字符.
你可以这样做:
name= name.replace('(', '').replace(')', '').replace ...
Run Code Online (Sandbox Code Playgroud)
要么:
name= ''.join(c for c in name if c not in '(){}<>')
Run Code Online (Sandbox Code Playgroud)
或者使用正则表达式:
import re
name= re.sub('[(){}<>]', '', name)
Run Code Online (Sandbox Code Playgroud)
Jas*_*uit 49
我在这里进行了一次时间测试,在循环中使用每种方法100000次.结果让我感到惊讶.(在回复评论中的有效批评后,结果仍然让我感到惊讶.)
这是脚本:
import timeit
bad_chars = '(){}<>'
setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""
timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ", timer.timeit(100000)
timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)
timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)
timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)
Run Code Online (Sandbox Code Playgroud)
结果如下:
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
Run Code Online (Sandbox Code Playgroud)
其他运行的结果遵循类似的模式.但是,如果速度不是主要考虑因素,我仍然认为string.translate最不可读; 其他三个更明显,但程度不同.
che*_*ish 17
string.translate with table = None工作正常.
>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
Run Code Online (Sandbox Code Playgroud)
Rue*_*uel 12
因为strip()根据您提供的内容仅剥离尾随和前导字符.我建议:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
Run Code Online (Sandbox Code Playgroud)
strip 仅从字符串的正面和背面剥离字符.
要删除字符列表,可以使用字符串的translate方法:
import string
name = "Barack (of Washington)"
table = string.maketrans( '', '', )
print name.translate(table,"(){}<>")
# Barack of Washington
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
163672 次 |
| 最近记录: |