我们可以多次使用re.sub代替str.replace吗

时间:2020-05-18 09:04:36

标签: python re

import re
a = ["%!It depends%% on what you m\\ean by dying.",
     "It is widely~ read and at the top_x000D_ of all the search%%__ engines.",
     "\\H~owever, Wikipedia has internal problems",
     "%%a+b!=a-b"]
p = [((((((str(a[i]).replace("%!", "")).replace("%", ""))
     .replace("~", "")).replace("_x000D_","")).replace("__", ""))
     .replace("\\", "")) for i in range(len(a)) if a[i] != ""]
print(p)

3 个答案:

答案 0 :(得分:1)

是的,您可以改用re.sub

p2 = [re.sub(r"%!|%|~|_x000D_|__|\\", "", str(a[i])) for i in range(len(a)) if a[i] != ""]

有关更多信息,请阅读以下文档:https://docs.python.org/3/library/re.html#re.sub

答案 1 :(得分:0)

自从导入re包以来,我认为您想以正则表达式的方式来完成此操作。

to_replace = ['%!', '%', '~', '_x000D_', '__', '\\']
to_replace = ")|(".join(map(re.escape, to_replace))
p = [re.sub(f'({to_replace})', '', a[i]) for i in range(len(a)) if a[i] != '']

建议使用re.escape以避免正则表达式中的无效符号。

答案 2 :(得分:0)

您可以使用

import re
a = ["%!It depends%% on what you m\\ean by dying.",
     "It is widely~ read and at the top_x000D_ of all the search%%__ engines.",
     "\\H~owever, Wikipedia has internal problems",
     "%%a+b!=a-b"]
pattern = re.compile(r'%!|_x000D_|__|[~%\\]')
p = [pattern.sub('', item) for item in a if item]
print(p)

哪个产量

['It depends on what you mean by dying.', 
 'It is widely read and at the top of all the search engines.',
 'However, Wikipedia has internal problems', 
 'a+b!=a-b']

请记住将更长的替换项留在交替中。