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)基本的に整数(2)なので使用できますre.IGNORECASEが、どの数値が「マッチケース」オプションを意味するのかわかりません。

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']場合matchCaseは印刷されます。1['Maki', 'maki']0

IDEONE デモを見る

于 2015-05-14T08:26:05.840 に答える