How to use operator.contains() method In Python
Approach
- Initiate a for loop to traverse list of strings and set res to False
- Check whether each string of list is present in given string
- If yes set res to True and break out of for loop
- Display res
Python3
# Python3 code to demonstrate # checking if string contains list element # initializing string import operator as op test_string = "There are 2 apples for 4 persons" # initializing test list test_list = [ 'apples' , 'oranges' ] # printing original string print ( "The original string : " + test_string) # printing original list print ( "The original list : " + str (test_list)) # checking if string contains list element res = False c = 0 for i in test_list: if (op.contains(test_string, i)): res = op.contains(test_string, i) break # print result print ( "Does string contain any list element : " + str (res)) |
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Time Complexity : O(M*N) M-length of test_list N-length of test_string
Auxiliary Space : O(1)
Approach#9:using lambda
Algorithm
1. Take the input string and a list of words from the user.
2. Define a lambda function contains_word() using lambda, map() and any() functions to check if any element from the list is present in the string.
3. Call the contains_word() function with the input string and the list of words as arguments.
4. Print the result.
Python3
string = "There are 2 apples for 4 persons" lst = [ 'apples' , 'oranges' ] # using lambda functions to check if string contains any element from list contains_word = lambda s, l: any ( map ( lambda x: x in s, l)) # printing the result if contains_word(string, lst): print ( "String contains at least one word from list." ) else : print ( "String does not contain any word from list." ) |
String contains at least one word from list.
Time complexity: O(n*m) where n is the length of the input string and m is the length of the list of words. This is because we are using the in operator to check if each element of the list is present in the string, which takes linear time.
Space complexity: O(n) where n is the length of the input string. This is because we are storing the input string in memory. The space used by the list of words and the lambda functions is negligible compared to the input string.
Python | Test if string contains element from list
We are given a String and our task is to test if the string contains elements from the list.
Example:
Input: String: Geeks for Geeks is one of the best company. List: ['Geeks', 'for'] Output: Does string contain any list element : True