Method # 1: Using List Comprehension
This problem can be solved by using list comprehension, in this we check the list, and also by using string elements if we can find a match. and return true if we find one and false does not use conditional statements.
# Python3 demo code # check if the string contains a list item # use comprehension list # initialization string test_string = " There are 2 apples for 4 persons " # initializing the test list test_list = [ ’apples’ , ’oranges’ ] # print original line print ( "The original string:" + test_string) # print the original list print ( "The original list:" + str (test_list)) # using comprehension list # check if the string contains a list item res = [ele for ele in test_list if (ele in test_string)] # print result print ( " Does string contain any list element: " + str ( bool (res))) |
Output:
The original string: There are 2 apples for 4 persons The original list: [’apples’,’ oranges ’] Does string contain any list element: True
Method # 2: using any()
Using any function is the most classic way in which you can accomplish this task, as well as efficiently. This function checks for a match in line with the match of each list item.
# Python3 demo code # check if string contains a list item # use comprehension list # initializing string test_string = "There are 2 apples for 4 persons" # initialize the test list test_list = [ ’apples’ , ’ oranges ’ ] # print original line print ( " The original string: " + test_string) # print the original list print ( "The original list : " + str (test_list)) # using comprehension list # check if the string contains a list item res = any (ele in < / code> test_string for ele in test_list) # print result print ( " Does string contain any list element: " + str (res) |
Output:
The original string: There are 2 apples for 4 persons The original list: [’apples’,’ oranges’] Does string contain any list element: True
Python | Check if a string contains an element from a list Python functions: Questions
Python | Check if a string contains an element from a list String Variables: Questions