我想从列表中删除所有需要的项目。这是我的代码如下:
filenameContainList = ["abc_001", "ZZ_ABC_dd_002", "abCXXyy_003", "PPP_004", "Fabc FABC FabC abc"]
userInputForRemove = ["abc","ppp"]
updatedFileNameList = []
import re
for i in userInputForRemove:
repat = "(.*){}(.*)".format(i)
for j in filenameContainList:
tmp = re.search(repat, j, re.IGNORECASE)
if tmp:
token = "".join(tmp.groups())
updatedFileNameList.append(token)
print(updatedFileNameList)
我的输出看起来像这样:
['_001', 'ZZ__dd_002', 'XXyy_003', 'Fabc FABC FabC ', '_004']
但是我希望输出看起来像这样:
['_001', 'ZZ__dd_002', 'XXyy_003', 'F F F ', '_004']
有人可以让我知道我在哪里犯错吗?
谢谢!
答案 0 :(得分:4)
尝试一下
import re
replace_ = re.compile("|".join(userInputForRemove), flags=re.IGNORECASE)
print([replace_.sub("", x) for x in filenameContainList])
['_001', 'ZZ__dd_002', 'XXyy_003', 'F F F ', '_004']