Python | Test if string contains element from list
During web development in Python, we generally come across a problem where we need to test if a particular element from a given list lies as sub-string or not. This kind of problem is also very common in Machine Learning domain. Let’s discuss certain ways in which this can be done. Show
Python3
Output : The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True
Python3
Output : The original string : There are 2 apples for 4 persons The original list : ['apples', 'oranges'] Does string contain any list element : True Article Tags : Python Python Programs Python list-programs Python string-programs Find a String in a List in PythonThere are various approaches to this problem, from the ease of use to efficiency. Using the ‘in’ operatorWe can use Python’s in operator to find a string in a list in Python. This takes in two operands a and b, and is of the form: ret_value = a in b Here, ret_value is a boolean, which evaluates to True if a lies inside b, and False otherwise. We can directly use this operator in the following way: a = [1, 2, 3] b = 4 if b in a: print('4 is present!') else: print('4 is not present') Output 4 is not present We can also convert this into a function, for ease of use. def check_if_exists(x, ls): if x in ls: print(str(x) + ' is inside the list') else: print(str(x) + ' is not present in the list') ls = [1, 2, 3, 4, 'Hello', 'from', 'AskPython'] check_if_exists(2, ls) check_if_exists('Hello', ls) check_if_exists('Hi', ls) Output 2 is inside the list Hello is inside the list Hi is not present in the list This is the most commonly used, and recommended way to search for a string in a list. But, for illustration, we’ll show you other methods as well. Using List ComprehensionLet’s take another case, where you wish to only check if the string is a part of another word on the list and return all such words where your word is a sub-string of the list item. Consider the list below: ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] If you want to search for the substring Hello in all elements of the list, we can use list comprehensions in the following format: ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [match for match in ls if "Hello" in match] print(matches) This is equivalent to the below code, which simply has two loops and checks for the condition. ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] matches = [] for match in ls: if "Hello" in match: matches.append(match) print(matches) In both cases, the output will be: ['Hello from AskPython', 'Hello', 'Hello boy!'] As you can observe, in the output, all the matches contain the string Hello as a part of the string. Simple, isn’t it? Using the ‘any()’ methodIn case you want to check for the existence of the input string in any item of the list, We can use the any() method to check if this holds. For example, if you wish to test whether ‘AskPython’ is a part of any of the items of the list, we can do the following: ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] if any("AskPython" in word for word in ls): print('\'AskPython\' is there inside the list!') else: print('\'AskPython\' is not there inside the list') Output 'AskPython' is there inside the list! Using filter and lambdasWe can also use the filter() method on a lambda function, which is a simple function that is only defined on that particular line. Think of lambda as a mini function, that cannot be reused after the call. ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi'] # The second parameter is the input iterable # The filter() applies the lambda to the iterable # and only returns all matches where the lambda evaluates # to true filter_object = filter(lambda a: 'AskPython' in a, ls) # Convert the filter object to list print(list(filter_object)) Output ['Hello from AskPython'] We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get! Python Check if List Contains a StringPython Python String Python List Created: June-02, 2021 | Updated: July-18, 2021 Strings are a sequence of characters. Just like strings store characters at specific positions, we can use lists to store a collection of strings. In this tutorial, we will get a string with specific values in a Python list. “python check list of words in string” Code Answercheck if word contains a word in a list python python by Worried Wildebeest on Jul 11 2020 Comment 1 Source: stackoverflow.com Add a Grepper Answer Python answers related to “python check list of words in string”
Python queries related to “python check list of words in string”
Check if element exists in list using python “in” OperatorCondition to check if element is in List : It will return True, if element exists in list else return false. For example check if ‘at’ exists in list i.e. Condition to check if element is not in List : ''' check if element NOT exist in list using 'in' ''' if 'time' not in listOfStrings : print("Yes, 'time' NOT found in List : " , listOfStrings) Advertisements Check if String Contains Substring in PythonLet’s look at all the different ways in Python to check if a string contains a substring. using find() methodfind() method is to verify if a string contains a substring or not. If the string contains a substring, it returns the starting index of the substring; else returns -1 if it cannot find a substring. Syntax: string.find(substring, start, end) Parameters:
OutputSubstring 'beautiful ' found at index: 12 6 -1 6 -1 Doesn't contains given substringUsing inoperatorThe “in” operator checks if a substring is present within a string, returnsTRUEif found else returnsFALSE. word = "Hello its a beautiful day" sub1="beautiful" sub2="sunny" print(sub1 in word) print(sub2 in word) #Output True Falseusing count() methodThe count() method checks for the occurrence of a substring in a string; if not found, return 0. word = "Hello its a beautiful day" sub1="beautiful" sub2="Hello" sub3="Sunny" print(word.count(sub1)) print(word.count(sub2)) print(word.count(sub3)) # Output 1 1 0using str.index() methodThe method checks that the given substring is present in a string. If the substring is not present in the string, it doesn’t return any value rather generates aValueError. Syntax: string.index(substring) word = "Hello its a beautiful day" try : result = word.index("beautiful") print ("beautiful is present in the string.") except : print ("beautiful is not present in the string.") # Output beautiful is present in the string.using operator.contains() methodUsing the operator module, we can search if the substring is present in a string. Syntax: operator.contains(string,substring) import operator word = "Hello its a beautiful day" if operator.contains(word, "beautiful"): print ("beautiful is present in the string.") else : print ("beautiful is not present in the string.") # Output beautiful is present in the string. |