2

我有字符串,来自一些 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

谢谢。

4

1 回答 1

1

只需将行更改为:

source = source.replace(i,"")

这是因为循环for i in mustDelWord已经遍历列表中的元素,而不是列表中的索引,所以你不必做mustDelWord[i].

于 2013-03-04T13:39:04.837 回答