2013-02-28 102 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' 
相关问题