简体   繁体   English

使用 Python 从列表中删除特定字符串,无论大小写如何

[英]Deleting particular string from list irrespective of uppercase/lowercase using Python

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:我的 output 看起来像这样:

['_001', 'ZZ__dd_002', 'XXyy_003', 'Fabc  FABC FabC ', '_004']

But I want output to look like this:但我希望 output 看起来像这样:

['_001', 'ZZ__dd_002', 'XXyy_003', 'F  F F ', '_004']

Can anyone let me know where I am making a mistake?谁能让我知道我在哪里犯了错误?

Thanks!谢谢!

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']

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

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