在python中删除基于某个列表的特定字符串

2024-05-05 18:47:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,来自某个xml元素:

source = "<![CDATA[<p><span stylefontfamily times new romantimesserif fontsize large>Is important ?</span></p>]]

““

我要删除基于此列表的指定字符串:

mustDelWord=["<p>","</p>","<span stylefontfamily times new romantimesserif fontsize large>","</span>"]

因此,预期输出为:

<![CDATA[Is important ?]]>

到目前为止,代码是:

mustDelWord=["<p>","</p>","<span stylefontfamily times new romantimesserif fontsize large>","</span>"]  

for i in mustDelWord:
        source = source.replace(mustDelWord[i],"")
print source

但出现以下错误:

source = source.replace(mustDelWord[i],"")

TypeError:列表索引必须是整数,而不是str

谢谢。你知道吗


Tags: 字符串source列表newisreplacelargespan
1条回答
网友
1楼 · 发布于 2024-05-05 18:47:01

只需将行更改为:

source = source.replace(i,"")

这是因为循环for i in mustDelWord已经在列表中的元素上迭代,而不是该列表中的索引,所以您不必执行mustDelWord[i]。你知道吗

相关问题 更多 >