简体   繁体   English

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

[英]Replace multiple occurrences inside a string in Python

I want to replace the following string with an empty string. 我想用空字符串替换以下字符串。

I cannot type in my inputs here, for some reason, those symbols are ignored here. 我不能在这里输入我的输入,由于某种原因,这些符号在这里被忽略。 Kindly look at the image below. 请看下面的图片。 My code produces weird results. 我的代码会产生奇怪的结果。 Kindly help me out here. 请帮助我。

#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

In python strings are immutable, ie doing any operation on a string always returns a new string object and leaves the original string object unchanged. 在python中,字符串是不可变的,即对字符串执行任何操作总是返回一个新的字符串对象,并保持原始字符串对象不变。

Example: 例:

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'
>>> import string
>>> s="A*B#C$D"
>>> a = string.maketrans("", "")
>>> s.translate(a, "*#$")
'ABCD'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM