我想用一个匹配的选项。我有一段代码可以搜索列表中的字符串。我想还有一种更优雅的方法来做同样的事情。
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“选项。
发布于 2015-05-14 08:26:05
您可以在理解中执行不区分大小写的搜索:
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']是1,则打印['Maki', 'maki'],如果设置为0,则打印['Maki', 'maki']。
请参阅IDEONE演示
https://stackoverflow.com/questions/30232253
复制相似问题