簡體   English   中英

Python strip() 多個字符?

[英]Python strip() multiple characters?

我想從字符串中刪除任何括號。 為什么這不能正常工作?

>>> name = "Barack (of Washington)"
>>> name = name.strip("(){}<>")
>>> print name
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)

我在這里做了一個時間測試,每個方法循環使用 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不是最易讀的; 其他三個比較明顯,雖然有不同程度的慢。

string.translate with table=None 工作正常。

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

因為strip()僅根據您提供的內容去除尾隨和前導字符。 我建議:

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

strip只從字符串的最前面和后面去除字符。

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

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

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

要僅刪除 s 中的括號,請嘗試以下方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM