我们可以多次使用 re.sub 而不是使用 str.replace
Can we use re.sub instead of using str.replace many time
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)
是的,您可以改用 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
既然你导入了 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
以避免正则表达式中的无效符号。
你可以使用
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']
记得把较长的替换放在交替的左边。
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)
是的,您可以改用 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
既然你导入了 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
以避免正则表达式中的无效符号。
你可以使用
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']
记得把较长的替换放在交替的左边。