2

我想使用匹配案例选项。我有一段代码来搜索列表中的字符串。我想有一种更优雅的方法可以做到这一点。

searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList = []
matchCase = 0

for item in itemList:
    if matchCase:
        if re.findall(searchString, item):
            resultList.append(item)
    else:
        if re.findall(searchString, item, re.IGNORECASE):
            resultList.append(item)

我可以使用re.findall(searchString, item, flags = 2),因为re.IGNORECASE基本上是一个整数 (2),但我不知道哪个数字意味着“matchcase”选项。

4

1 回答 1

3

您可以在理解中强制执行不区分大小写的搜索:

searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList =[]
matchCase = 1

if matchCase:
    resultList = [x for x in itemList if x == searchString]
else:
    resultList = [x for x in itemList if x.lower() == searchString.lower()]

print resultList

它将打印['maki']if matchCaseis 1['Maki', 'maki']如果它设置为0

IDEONE 演示

于 2015-05-14T08:26:05.840 回答