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 に答える