Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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']
like image 776
onlyo Avatar asked Jan 21 '26 11:01

onlyo


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'] 
like image 148
Mark Avatar answered Jan 24 '26 02:01

Mark