Python Return case insensitive string from a list, if it contains case insensitive substring

Viewed 94

How can I return case insensitive string from a list, if it contains case insensitive substring? The returned string should be case insensitive

I was able to return string from the list, but I'm using the lowercase method. I would like to return it to its original state without modifying

entriesList = ['CSS', 'Django', 'Git', 'HTML', 'Python']

substring = "g"

def substringSearch(substring, entriesList):
  return [string for string in (string.casefold() for string in entriesList) if substring in string] 


print(substringSearch(substring, entriesList))

Result:

['django', 'git']

What I would like to get:

['Django', 'Git']
1 Answers

You can just use the lower() or casefold() in the test in comprehension.

[string for string in entriesList if substring in string.casefold()]

You don't need to make a new generator for this. That will give you:

entriesList = ['CSS', 'Django', 'Git', 'HTML', 'Python']

substring = "g"

def substringSearch(substring, entriesList):
      return [string for string in entriesList if substring in string.casefold()] 


print(substringSearch(substring, entriesList))

# ['Django', 'Git'] 
Related