0

我想用空字符串替换以下字符串。

我不能在这里输入我的输入,由于某种原因,这些符号在这里被忽略了。请看下面的图片。我的代码产生了奇怪的结果。请在这里帮助我。

#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
4

2 回答 2

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'
于 2013-02-28T00:41:24.567 回答
0
>>> import string
>>> s="A*B#C$D"
>>> a = string.maketrans("", "")
>>> s.translate(a, "*#$")
'ABCD'
于 2013-03-27T12:56:08.957 回答