2013-08-30 43 views
6

我有用點分隔的字符串。 實施例:Python:去掉通配符字

string1 = 'one.two.three.four.five.six.eight' 
string2 = 'one.two.hello.four.five.six.seven' 

如何使用這個串中的蟒方法,分配一個字作爲通配符(因爲在這種情況下,例如第三字而異)。我正在考慮正則表達式,但不知道像Python這樣的方法在python中是否有可能。 例如:

string1.lstrip("one.two.[wildcard].four.") 

string2.lstrip("one.two.'/.*/'.four.") 

(我知道我可以通過split('.')[-3:]提取這一點,但我正在尋找一個普遍的方式,lstrip只是一個例子)

回答

18

使用re.sub(pattern, '', original_string)中刪除匹配的部分original_string

>>> import re 
>>> string1 = 'one.two.three.four.five.six.eight' 
>>> string2 = 'one.two.hello.four.five.six.seven' 
>>> re.sub(r'^one\.two\.\w+\.four', '', string1) 
'.five.six.eight' 
>>> re.sub(r'^one\.two\.\w+\.four', '', string2) 
'.five.six.seven' 

順便說一句,你是誤會str.lstrip

>>> 'abcddcbaabcd'.lstrip('abcd') 
'' 

str.replace是比較合適的(當然,應用re.sub,太):

>>> 'abcddcbaabcd'.replace('abcd', '') 
'dcba' 
>>> 'abcddcbaabcd'.replace('abcd', '', 1) 
'dcbaabcd' 
+0

謝謝!而對於你的「順便說一句」:是否有可能剝奪以正確方式排列的「abcd」?或者這只是一個正則表達式的情況? – aldorado

+0

@aldorado,''abcddcbaabcd'.replace('abcd','',1)'。 '1'表示只替換一次。 – falsetru

+2

@aldorado,我添加了另一個顯示'str.replace'的示例用法的代碼。 – falsetru