2013-02-28 91 views
0

我想用空字符串替換下面的字符串。在Python中用一個字符串替換多個出現

我不能在這裏鍵入我的輸入,出於某種原因,這些符號在這裏被忽略。請看下面的圖片。我的代碼產生奇怪的結果。請在這裏幫助我。

#expected output is "A B C D E" 

string = "A<font color=#00FF00> B<font color=#00FFFF> C<font color="#00ff00"> D<font color="#ff0000"> E<i>" 

lst = ['<i>','<font color=#00FF00>','<font color=#00FFFF>','<font color="#00ff00">','<font color="#ff0000">'] 

for el in lst: 
    string.replace(el,"") 
print string 
+1

嘗試'字符串=與string.replace(EL 「」)' – 2013-02-28 00:37:32

+0

如果您的問題實際上是在一個字符串剝離HTML標記,你應該看看那個其他問題:http://stackoverflow.com/questions/753052/strip-html-from-strings-in-python – alexisdm 2013-02-28 00:46:15

回答

2

在python字符串中是不可變的,即對字符串做任何操作總是返回一個新的字符串對象並保持原始字符串對象不變。

例子:

In [57]: strs="A*B#C$D" 

In [58]: lst=['*','#','$'] 

In [59]: for el in lst: 
    ....:  strs=strs.replace(el,"") # replace the original string with the 
             # the new string 

In [60]: strs 
Out[60]: 'ABCD' 
0
>>> import string 
>>> s="A*B#C$D" 
>>> a = string.maketrans("", "") 
>>> s.translate(a, "*#$") 
'ABCD' 
相關問題