How to use case-agnostic-string-matching-condition in a Python list comprehension?

107 views Asked by At

Is there a way to make a list comprehension to search for a string being case insensitive?

What I do now, which is subpar is:


original_list = ['NAME', 'NUMBER', 'name', 'number', 'Name', 'NaMe', 'place']

filtered_list = [x for x in LIST if "NAME" in x or "name" in x]

This example would exclude "Name" and "NaMe" (which I want to be included) for example. The idea is to use a list comprehension and have a short and concise way of doing this.

I would like to do something like this:


case_insensitive_list = [x for x in LIST if 'name'.caseinsensitive() in x]

(it seems after the second OR the list comprehension begins to behave weird.)

I CANNOT use the str.upper() strategy, I need to retain the case of the original list.

I am expecting a simple list comprehension with a case agnostic string matching condition.

My expected outcome:

['NAME', 'name', 'Name', 'NaMe']
3

There are 3 answers

4
webelo On

I CANNOT use the str.upper() strategy, I need to retain the case of the original list.

The original list is not affected if you do this in the if condition only:

LIST = ['NAME', 'NUMBER', 'name', 'number', 'Name', 'NaMe', 'place']

filtered_list = [x for x in LIST if "name" in x.lower()]


print(filtered_list)
# ['NAME', 'name', 'Name', 'NaMe']


print(LIST)
# ['NAME', 'NUMBER', 'name', 'number', 'Name', 'NaMe', 'place']
2
Johnny John Boy On

Pretty simple, you just need to turn each item in the list to uppercase and check against the uppercase "NAME" list this.

It might also be wise to get in the habit of not calling lists LIST or list.

my_list = ['NAME', 'NUMBER', 'name', 'number', 'Name', 'NaMe', 'place']

filtered_list = [x for x in my_list if "NAME"==x.upper()]

print(filtered_list)
# ['NAME', 'name', 'Name', 'NaMe']
1
chepner On

You could always use the re module.

import re

LIST = ['NAME', 'NUMBER', 'name', 'number', 'Name', 'NaMe', 'place']
filtered_list = [x for x in LIST if re.match("name", x, re.IGNORECASE)]