Naive Approach checking each word in the string
Here we are splitting the string into list of words and then matching each word of this list with the already present list of words we want to check.
Python3
# initializing string 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)) test_string = test_string.split( " " ) flag = 0 for i in test_string: for j in test_list: if i = = j: flag = 1 break if flag = = 1 : print ( "String contains the list element" ) else : print ( "String does not contains the list element" ) |
Output
The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] String contains the list element
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
Contact Us