Reputation: 39
I want to delete all desired items from the list. This is my code below:
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)
My output looks like this :
['_001', 'ZZ__dd_002', 'XXyy_003', 'Fabc FABC FabC ', '_004']
But I want output to look like this :
['_001', 'ZZ__dd_002', 'XXyy_003', 'F F F ', '_004']
Can anyone let me know where I am making a mistake?
Thanks!
Upvotes: 0
Views: 68
Reputation: 8302
try this,
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']
Upvotes: 4