我想使用匹配案例选项。我有一段代码可以在列表中搜索字符串。我想有一种更优雅的方法可以做到这一点。
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) 但我不知道是哪个数字将意味着“匹配案例”选项。
请您参考如下方法:
您可以在推导式中执行不区分大小写的搜索:
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
如果 matchCase 为 1 并且 ['Maki', 'maki'] ,它将打印 如果它设置为 ['maki'] 0。
参见 IDEONE demo
