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