Python case insensitive efficiently check if list of strings is contained in another string

86 Views Asked by At

I want to check if a list of string is contained in another string but ignoring the case

For example:

Input: 'Hello World', ['he', 'o w']
Output: [True, True]
Input: 'Hello World', ['he', 'wol']
Output: [True, False]

I can write something like:

output =[]
for keyword in keywordlist:
  if keyword.lower() in string.lower():
    output.append(True)
  else:
    output.append(False)

But the issues with this are:

  1. the time complexity
  2. using lower()

I have found this question on stack overflow which is similar Check if multiple strings exist in another string

But it doesn’t work for ignore case.

Is there an efficient way to do this?

1

There are 1 best solutions below

0
SIGHUP On

This is probably quite efficient:

# make sure the input string is lowercase - do this only once
string = 'Hello World'.lower()
keywordlist = ['he', 'o w'] # all keywords assumed to be lowercase
output = [kw in string for kw in keywordlist]
print(output)

Output:

[True, True]