Python strip()多个字符?

我想从string中删除任何括号。 为什么这不能正常工作?

>>> name = "Barack (of Washington)" >>> name = name.strip("(){}<>") >>> print name Barack (of Washington 

我在这里做了一次时间testing,每个方法循环使用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()所做的。 它将删除参数中存在的前导字符和尾随字符,但不会删除string中间的字符。

你可以这样做:

 name= name.replace('(', '').replace(')', '').replace ... 

要么:

 name= ''.join(c for c in name if c not in '(){}<>') 

或者使用正则expression式:

 import re name= re.sub('[(){}<>]', '', name) 

string.translate与表= None 无法正常工作。

 >>> name = "Barack (of Washington)" >>> name = name.translate(None, "(){}<>") >>> print name Barack of Washington 

由于strip()仅根据您提供的内容去除尾随和前导字符。 我build议:

 >>> import re >>> name = "Barack (of Washington)" >>> name = re.sub('[\(\)\{\}<>]', '', name) >>> print(name) Barack of Washington 

strip仅从string的正面和背面剥离字符。

要删除字符列表,您可以使用string的translate方法:

 import string name = "Barack (of Washington)" table = string.maketrans( '', '', ) print name.translate(table,"(){}<>") # Barack of Washington 

例如,strings="(U+007c)"

要从s删除括号,请尝试下面的一个:

 import re a=re.sub("\\(","",s) b=re.sub("\\)","",a) print(b)