在Python中替换字符串中的多个匹配项

2024-07-08 16:52:10 发布

您现在位置: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

Tags: 字符串代码outputstringis符号图片原因
2条回答
>>> import string
>>> s="A*B#C$D"
>>> a = string.maketrans("", "")
>>> s.translate(a, "*#$")
'ABCD'

在python中,字符串是不可变的,即对字符串执行任何操作都会返回一个新的string对象,并保持原始string对象不变。在

示例:

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'

相关问题 更多 >

    热门问题