我想从字符串中删除任何括号。为什么这不能正常工作?Python strip()多个字符?
>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington
我想从字符串中删除任何括号。为什么这不能正常工作?Python strip()多个字符?
>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
Barack (of Washington
我在这里做一个时间测试,使用各种方法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)
下面是结果:对其他运行
List comprehension: 0.631745100021
Regular expression: 0.155561923981
Replace in loop: 0.235936164856
string.translate: 0.0965719223022
结果遵循类似的模式。但是,如果速度不是主要问题,我仍然认为string.translate
不是最可读的;其他三个比较明显,虽然速度有所不同。
strip
只从字符串的正面和背面剥去字符。
要删除字符的列表,你可以使用字符串的方法translate
:
import string
name = "Barack (of Washington)"
table = string.maketrans('', '',)
print name.translate(table,"(){}<>")
# Barack of Washington
因为这不是strip()
所做的。它删除参数中存在的前导字符和尾随字符,但不删除字符串中间的字符。
你可以这样做:
name= name.replace('(', '').replace(')', '').replace ...
或:
name= ''.join(c for c in name if c not in '(){}<>')
或可能使用正则表达式:
import re
name= re.sub('[(){}<>]', '', name)
因为strip()
只带尾随和前导字符,根据你提供。我建议:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
在正则表达式字符类中,你不需要转义任何东西,所以'[(){} <>]'很好 – 2010-10-10 17:16:04
string.translate与表=无效正常工作。
>>> name = "Barack (of Washington)"
>>> name = name.translate(None, "(){}<>")
>>> print name
Barack of Washington
这在Python中不起作用3表示字符串,仅用于字节和bytearray。 – 2018-02-26 20:40:40
例如串s="(U+007c)"
要删除只从s括号,请尝试以下之一:
import re
a=re.sub("\\(","",s)
b=re.sub("\\)","",a)
print(b)
这是如何消除括号?通过删除任何不是字母数字的东西? – 2017-08-06 11:52:32
当问题显示“删除括号”,但您的答案显示“删除不是字母数字的任何内容”时,我认为您没有解决问题。 – 2017-08-06 11:57:57
感谢这 - 的教育问题,我不仅了解到,带()没有做到我的想法,我也学会了三种其他的方式来达到我想要的,而且是最快的! – AP257 2010-10-11 15:53:40
不会为unicode工作:translate()只需要一个参数(表)与unicode。 – rikAtee 2013-07-16 18:32:22
减1:为了使速度应该是关于代码清晰度和鲁棒性的东西。 – jwg 2016-01-05 10:52:47