2010-10-10 1495 views
40

我想從字符串中刪除任何括號。爲什麼這不能正常工作?Python strip()多個字符?

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

回答

31

我在這裏做一個時間測試,使用各種方法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不是最可讀的;其他三個比較明顯,雖然速度有所不同。

+1

感謝這 - 的教育問題,我不僅瞭解到,帶()沒有做到我的想法,我也學會了三種其他的方式來達到我想要的,而且是最快的! – AP257 2010-10-11 15:53:40

+1

不會爲unicode工作:translate()只需要一個參數(表)與unicode。 – rikAtee 2013-07-16 18:32:22

+4

減1:爲了使速度應該是關於代碼清晰度和魯棒性的東西。 – jwg 2016-01-05 10:52:47

7

strip只從字符串的正面和背面剝去字符。

要刪除字符的列表,你可以使用字符串的方法translate

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

因爲這不是strip()所做的。它刪除參數中存在的前導字符和尾隨字符,但不刪除字符串中間的字符。

你可以這樣做:

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

或:

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

或可能使用正則表達式:

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

因爲strip()只帶尾隨和前導字符,根據你提供。我建議:

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

在正則表達式字符類中,你不需要轉義任何東西,所以'[(){} <>]'很好 – 2010-10-10 17:16:04

15

string.translate與表=無效正常工作。

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

這在Python中不起作用3表示字符串,僅用於字節和bytearray。 – 2018-02-26 20:40:40

-2

例如串s="(U+007c)"

要刪除只從s括號,請嘗試以下之一:

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

這是如何消除括號?通過刪除任何不是字母數字的東西? – 2017-08-06 11:52:32

+0

當問題顯示「刪除括號」,但您的答案顯示「刪除不是字母數字的任何內容」時,我認爲您沒有解決問題。 – 2017-08-06 11:57:57