Python find word in list

In Python, finding a specific word or element within a list is a familiar task developers often search for. This tutorial will teach us four effective methods to find a word in a list.

Method 1: Using the ‘in’ Keyword

We can use the in keyword to find a word in a list. The in keyword is a membership operator that returns True if the word is present in the list and False if it is not. 

Find a word in a list

For example, let’s say you have a list called «my_list» that contains the following elements:

my_list = ["java", "python", "jquery", "php"]

And you want to find the python word in this list.

# Define a list of items
my_list = ["java", "python", "jquery", "php"]

# Check if the word "python" is present in the list
if "python" in my_list:
    # If "python" is present, print this message
    print("The word 'python' is present in the list.")
else:
    # If "python" is not present, print this message
    print("The word 'python' is not present in the list.")

Output:

The word 'python' is present in the list.

As you can see, the program finds the word python in the my_list and returns The word ‘python’ is present in the list.

Find multi-words in a list

To find multi-words in the list, we need to set another list that contains words to find.

# Define a list of words
my_list = ["java", "python", "jquery", "php"]

# Define a list of words to find
words_to_find = ["python","php"]

# Iterate through words_to_find
for word in words_to_find:
    
  # Check if word is present in my_list
  if word in my_list:
    # If word is present, print this message
    print(f"'{word}' is present in the list")
    
  else:
    # If word is not present, print this message
    print(f"'{word}' is not present in the list")

Output:

'python' is present in the list
'php' is present in the list

In the above code we:

  1. defined a list called my_list which contains the elements «java», «python», «jquery», and «php».
  2. defined another list called words_to_find which contains the elements to find.
  3. used a for loop to iterate through the words_to_find list.
  4. used the in keyword to check if the word is present in the my_list.

Method 2: Using the index() method

By using the index() method, we can find a word in a list. However, this method returns the index of the first occurrence of the specified word in the list.

Here is the syntax of the index()

list_or_tuple.index(item, start, end)
  • item is the item that you want to find the index of.
  • start (optional) parameter the starting index from where the search should begin.
  • end (optional) the ending index where the search should end.

In our situation, we will use the item parameter. In the following example, we’ll find the word python.

# List
my_list = ["java", "python", "jquery", "php"]

# finds the index of "python" in the list
index = my_list.index("python")

# prints the index of "python" in the list
print("The word 'python' is present at index", index)

Output:

The word 'python' is present at index 1

As we can see, the program found the word python in my_list and returned the index of the word. As we know, every list starts with an index of 0

The index() method is more powerful than the in keyword because it provides the index of the word in the list. If the word is not present will raise a ValueError, as in the following example.

# List
my_list = ["java", "python", "jquery", "php"]

# finds the index of "ruby" in the list
index = my_list.index("ruby")

# prints result
print("The word 'python' is present at index", index)

Output:

ValueError: 'ruby' is not in list

So you will need to add a try-except syntax to handle this case. Let’s see how we can do that.

try:
    # List
    my_list = ["java", "python", "jquery", "php"]
    
    # finds the index of "ruby" in the list
    index = my_list.index("ruby")
    
    # prints result
    print("The word 'ruby' is present at index", index)
    
except:
    print("The word 'ruby' is not present at list")

Output:

The word 'ruby' is not present at list

Method 3: Using the count() method

The count() is a method to count a specific word in a list. But it can also be used to check if a word is present in the list.

Here is count() syntax:

list.count(element)

Now, let’s see an example:

# List
my_list = ["java", "python", "jquery", "php"]

# Word to Find
word_to_find = "python"

# Count word in the list
count = my_list.count(word_to_find)

# IF Count returns greater than 1
if count:
    print(f"word {word_to_find} is in my_list")
    
else:
    print(f"word {word_to_find} is not in my_list")

Output:

word python is in my_list

Our code above counts the number of occurrences of word_to_find in the my_list. The word is found in the list if the count is greater than 0.

Further, you can also use the count to find multiple words in a list. Let us see an example.

# List
my_list = ["java", "python", "jquery", "php"]

# Word to Find
list_to_find = ["python", "php"]

for w in list_to_find:
    
    # Count word in the list
    count = my_list.count(w)
    
    # IF Count return more than 1
    if count:
        print(f"word {w} is in my_list")
        
    else:
        print(f"word {w} is not in my_list")

Output:

word python is in my_list
word php is in my_list

From the above example, you can see that we have set another list of words to find and iterate over it.

Method 4: Using List Comprehension

The last method of this tutorial is List Comprehension. List comprehension is a concise way of creating a new list in Python. It consists of an expression followed by a for clause, and zero or more if clauses.

Let us see how we can use it to find a word in a list with the help of an example.

my_list = ["java", "python", "jquery", "php"]

# word to find in the list
word_to_find = "php"

# using list comprehension to find all indexes of word_to_find
result = [i for i, x in enumerate(my_list) if x == word_to_find]

# print the result
print("The word 'php' appears at indexes:", result)

Output:

The word 'python' appears at indexes: [3]

This method finds the word in the list and gives you the index of that word because we use the enumerate() built function to add a counter to an iterable.

Conclusion

All right, In this article, we have discussed four different methods for finding a word in a list in Python. We have also discussed how to find multiple words.

Each method has its advantages and disadvantages. And the best way for a particular situation will depend on the specific requirements of the task. 

Finally, I hope this article helps you find your response.
Happy Coding

In this article, we’ll take a look at how we can find string in list in Python


There are three ways to find a string in a list in Python. They’re as follows:

  1. With the in operator in Python
  2. Using list comprehension to find strings in a Python list
  3. Using the any() method to find strings in a list
  4. Finding strings in a list using the filter and lambda methods in Python

Let’s get right into the individual methods and explore them in detail so you can easily implement this in your code.

1. Using the ‘in’ operator to find strings in a list

In Python, the in operator allows you to determine if a string is present a list or not. The operator takes two operands, a and b, and the expression a in b returns a boolean value.

If the value of a is found within b, the expression evaluates to True, otherwise it evaluates to False.

Here, ret_value is a boolean, which evaluates to True if a lies inside b, and False otherwise.

Here’s an example to demonstrate the usage of the in operator:

a = [1, 2, 3]

b = 4

if b in a:
    print('4 is present!')
else:
    print('4 is not present')

Output

To make the process of searching for strings in a list more convenient, we can convert the above into a function. The following example illustrates this:

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

The in operator is a simple and efficient way to determine if a string element is present in a list. It’s the most commonly used method for searching for elements in a list and is recommended for most use cases.


2. Using List Comprehension to find strings

Let’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.

List comprehensions can be a useful tool to find substrings in a list of strings. In the following example, we’ll consider a list of strings and search for the substring “Hello” in all elements of the list.

Consider the list below:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

We can use a list comprehension to find all elements in the list that contain the substring “Hello“. The syntax is as follows:

ls = ['Hello from AskPython', 'Hello', 'Hello boy!', 'Hi']

matches = [match for match in ls if "Hello" in match]

print(matches)

We can also achieve the same result using a for loop and an if statement. The equivalent code using a loop is as follows:

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?


3. Using the ‘any()’ method

The any() method in Python can be used to check if a certain condition holds for any item in a list. This method returns True if the condition holds for at least one item in the list, and False otherwise.

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')

In the above example, the condition being checked is the existence of the string "AskPython" in any of the items in the list ls. The code uses a list comprehension to iterate over each item in the list and check if the condition holds.

If the condition holds for at least one item, any() returns True and the first if statement is executed. If the condition does not hold for any item, any() returns False and the else statement is executed.

Output

'AskPython' is there inside the list!

4. Using filter and lambdas

We 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

We do have what we expected! Only one string matched with our filter function, and that’s indeed what we get!


Conclusion

We have seen that there are various ways to search for a string in a list. These methods include the in operator, list comprehensions, the any() method, and filters and lambda functions. We also saw the implementation of each method and the results that we get after executing the code. To sum up, the method you use to find strings in a list depends on your requirement and the result you expect from your code. It could be a simple existence check or a detailed list of all the matches. Regardless of the method, the concept remains the same to search for a string in a list.


References

  • JournalDev article on finding a string in a List
  • StackOverflow question on finding a string inside a List

so my program will require the user to input a phrase WITHOUT punctuation and the program will return its position in the list.

def Detection():
        print(list.index(find))
        find_found=list.index(find)
        list[find_found]="hide"
list = input("Enter a phrase without punctuation:")
print(list) 
list = list.split(" ")
list = [element.lower() for element in list]
find=input("what word must be found?")
find=find.lower()
if find in list:
for find in list:
    Detection()
else:
    print("its not in the list.")

Łukasz Rogalski's user avatar

asked May 20, 2016 at 8:31

ender's user avatar

1

l = [«enter», ‘a’, ‘phrase’]

l.index(‘a’)

which returns index if word is not there in list throws ValueError Exception.

to get indexes for duplicates also

sorted_list = sorted(l)
first_ind = sorted_list.index("enter")
last_ind = len(sorted_list) - sorted_list[::-1].index("enter") - 1
indexes = range(first_ind, last_ind + 1)

answered May 20, 2016 at 8:48

Harsha Komarraju's user avatar

1

i found a way here it is.

sentence =input("phrase to be shortened: ")
print (sentence)
text = input("Choose a word from the sentence above: ")
sentence = sentence.upper()
sentence = sentence.split(" ")
text = text.upper ()# this makes the text in capital letters
def lookfor (text):
    indexes = [ idx+1 for word, idx in zip(sentence, range(0,len(sentence))) if text == word ]
    print ("Your word has been found in the sentence at these positions", indexes )

    if not indexes:
         print ("The word that you have typed is not found in the sentence.")

lookfor(text)

answered May 31, 2016 at 11:12

ender's user avatar

enderender

154 bronze badges

We got to know about many topics in python. But have you ever tried to find the string in a list in Python? In this tutorial, we will be focusing on finding the string in a list. There are multiple ways through which we can find the string in a list. We will be discussing all of them in this article.

We will find the string in a python list with multiple ways like for loop, in operator, using count, any() function.

5 Ways With Examples to Find The String In List in Python

We will discuss how we can find the string in a list with examples explained in detail.

1. Using Simple For Loop

In this example, we will be making a list with elements of a string. We will then take an input string from the user, which we want to find that the string contains in a list. By using for loop, we will find the string in a list. Let us look in detail with the help of the example explained below:

#input list
lst = ['abc', 'def', 'ghi','python', 'pool']

#input string from user
str = input("Enter the input string : ")
c = 0
#applying loop
for i in lst:
    if i == str:
        c = 1
        break
if c == 1:
    print("String is present")
else:
    print("String is not present")

Output:

Enter the input string : python
String is present

Explanation:

  • Firstly, we will make a list that will contain some element in the form of a string.
  • Then, we will take the input from the user in the form of a string.
  • We will take a variable c which is set to 0.
  • After that, we will be applying for loop.
  • Inside for loop, we will apply if condition in which we will check if the element of the list is equal to the string. If they are equal c value becomes 1, and the loop gets breaks.
  • At last, we will check if c is equal to 1 or 0. if c is equal to 1, we will print string is present and if c == 0, we will print string is not present.
  • Hence, you can see the output.

2. Using in operator to Find The String List in Python

It is the membership operator in python. It is used to test whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary).

In this example, we will be making a list with elements of a string. We will apply in operator if we give the string to be searched and check if it is in the list. Let us look in detail with the help of the example explained below:

#input list
lst = ['abc', 'def', 'ghi','python', 'pool']

#applying if condition
if 'pool' in lst:
    print("string is present")
else:
    print("string is not present")

#checking false condition
if 'pools' in lst:
    print("string is present")
else:
    print("string is not present")

Output:

string is present
string is not present

Explanation:

  • Firstly, we will make a list that will contain some element in the form of a string.
  • Then, we will apply the ‘in’ operator inside the if condition and check if the string we want to check is present in the given list or not.
  • If the string is present, the output is printed as the string is present, and if the string is not present, the output is printed as the string is not present.
  • We have taken both examples. One of the lists is present, and one of the lists is not present in the program.
  • Hence, you can see the output.

3. Using count() function

The count() function is used to count the occurrences of a string in a list. If we get the output as 0, then it says that the string does not contain the list, and if the output is 1, then the string is present in the list.

In this example, we will be making a list with elements of a string. We will then take an input string from the user, which we want to find that the string contains in a list. Then, we will apply the count function passing the input string and see the count value through the if condition, and print the output.

#input list
lst = ['abc', 'def', 'ghi','python', 'pool']

#input string from user
str = input("Enter the input string : ")

#count function
count = lst.count(str)

if count > 0:
    print("String is present")
else:
    print("String is not present")

Output:

Enter the input string : ghi
String is present

Explanation:

  • Firstly, we will make a list that will contain some element in the form of a string.
  • Then, we will take the input from the user in the form of a string.
  • Then, we will apply the count() function, which will count the string’s occurrence in a list.
  • If the count’s value is equal to 0, the output will be printed as the string is not present, and if the count is greater than 0, the output is printed as the string is present in the list.
  • Hence, you can see the output.

4. Using any() function to Find String In List in Python

The any() function returns True if the string is present in a list. Otherwise, it returns False. If the list is empty, it will return False.

In this example, we will be making a list with elements of a string. We will apply if condition, and in that, we will apply any() function through which we can find the string in a list is present or not.

#input list
lst = ['abc', 'def', 'ghi','python', 'pool']
 
if any("pool" in word for word in lst):
    print("string is present")
else:
    print("string is not present")

Output:

string is present

Explanation:

  • Firstly, we will make a list that will contain some element in the form of a string.
  • Then, we will apply any() function inside the condition where we will give the string we have to find and apply for loop.
  • If the function finds any same string as given, the output gets printed as the string is present, and if it does not find any such string, the output gets printed as a string is not present.
  • Hence, you can finally see the output as the string is present as the pool is present in the list.

5. Finding all the indexes of a particular string

In this example, we will be making a list with elements of a string. Then, we will be selecting a particular string and try to find all the indexes at which the string is present. We will be using len() function for finding the length of the list and while loop for running the loop from starting till the end of the list.

#input list
lst = ['A','D', 'B', 'C', 'D', 'A', 'A', 'C', 'D']
s = 'D'
index = []
i = 0
length = len(lst)

while i < length:
    if s == lst[i]:
        index.append(i)
    i += 1
print(f'{s} is present in {index}')

Output:

D is present in [1, 4, 8]

Explanation:

  • Firstly, we will make a list that will contain some element in the form of a string.
  • Then, We will take a particular string of which we want to find the present indexes.
  • After that, we will make an empty list as index and keep i=0.
  • Then, we will calculate the length of the list.
  • After that, we will apply while loop till the length of the list and check the condition if the string is preset at that index of list or not.
  • If present we will store the index value in the new list index and continue the loop till the end.
  • At last, we will print all the indexes.

Conclusion

In this tutorial, we have learned about how to find the string in a list. We have seen all the multiple methods through which we can find the string present in the list. We have also discussed all the methods with the examples explained in detail. You can use any of the methods according to your need in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Given a list, the task is to write a Python program to check whether a list contains a particular string or not.

Examples:

Input: l=[1, 1.0, 'have', 'a', 'geeky', 'day']; s='geeky'
Output: geeky is present in the list
Input: l=['hello',' geek', 'have', 'a', 'geeky', 'day']; s='nice'
Output: nice is not present in the list

Method #1: Using in operator

The in operator comes handy for checking if a particular string/element exists in the list or not.

Example:

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky' 

if s in l:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

geeky is present in the list

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using count() function

The count() function is used to count the occurrence of a particular string in the list. If the count of a string is more than 0, it means that a particular string exists in the list, else that string doesn’t exist in the list.

Example:

Python3

l = ['1', 1.0, 32, 'a', 'geeky', 'day']

s = 'prime'

if l.count(s) > 0:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

prime is not present in the list

Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), no extra space is required

Method #3: Using List Comprehension

List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. It is used to transform iterative statements into formulas.

Example:

Python3

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'geek'

compare = [i for i in l if s in l]

if len(compare) > 0:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

geeky is present in the list

Method #4: Using any() function

The any() function is used to check the existence of an element in the list. it’s like- if any element in the string matches the input element, print that the element is present in the list, else, print that the element is not present in the list.

Example:

Python3

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'prime'

if any(s in i for i in l):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:

prime is not present in the list

The time and space complexity for all the methods are the same:

Time Complexity: O(n) -> as the built-in operators and functions like ‘in’, ‘count’ take O(n)

Space Complexity: O(n)

Method #5 : Using  list(),map(),join(),find() methods

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

nl=list(map(str,l))

x=" ".join(nl)

if x.find(s)!=-1:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity: O(n) -> built-in functions like join takes O(n)

Space Complexity: O(n)

Method #6 : Using Counter() function

Python3

from collections import Counter

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

freq = Counter(l)

if s in freq.keys():

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity: O(n) 

Auxiliary Space: O(n)

Method 7:  using operator.countOf() method

Python3

import operator as op

l = ['1', 1.0, 32, 'a', 'geeky', 'day']

s = 'prime'

if op.countOf(l, s):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

prime is not present in the list

Time Complexity: O(N)

Auxiliary Space : O(1)

Method :  using try/except and index()

You can use the index() method to find the first index of a string in a list. If the string is present in the list, the index() method returns the first index of the string, otherwise it raises a ValueError. To check if a string is present in a list, you can wrap the index() method in a try-except block, and print a message indicating whether the string is present in the list or not.

Python3

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

try:

    index = l.index(s)

    print(f'{s} is present in the list at index {index}')

except ValueError:

    print(f'{s} is not present in the list')

Output

geeky is present in the list at index 4

Time Complexity: O(n) where n is the number of elements in the list, as the index() method iterates over the elements of the list until it finds the desired string or it exhausts the list.

Auxiliary Space: O(1), as the method uses only a few constant-sized variables, regardless of the size of the list.

Method : Using re

Algorithm

  1. Initialize a list l and a string s.
  2. Import the re module.
  3. Use the re.search() function to search for the string s in the list l.
  4. If a match is found, print that the string s is present in the list.
  5. If no match is found, print that the string s is not present in the list.

Python3

import re

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

for item in l:

    if isinstance(item, str) and re.search(s, item):

        print(f'{s} is present in the list')

        break

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time complexity: O(n*m), where n is the number of items in the list and m is the length of the longest string in the list.
Auxiliary Space: O(1), as we are not using any additional data structures in the program.

Method : Using operator.contains()

Approach

  1. Check whether given string is present in list using operator.contains()
  2. If yes display “string” is present in the  list
  3. If not display “string” is not present in the list

Python3

import operator

l = [1, 2.0, 'have', 'a', 'geeky', 'day']

s = 'geeky'

if operator.contains(l, s):

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output

geeky is present in the list

Time Complexity : O(N) N – length of list
Auxiliary Space : O(1)

Method : Using numpy:

  1. Import the numpy module.
  2. Initialize a list variable l with some string values.
  3. Initialize a string variable s with the value “prime”.
  4. Use a list comprehension to create a list of boolean values, where each value corresponds to whether the
  5. string s is present in the corresponding element of the list l.
  6. Use the np.any() method to check if any of the values in the resulting list is True.
  7. Print a message indicating whether the string s is present in the list or not, based on the value of res.

Python3

import numpy as np

l = ['hello', 'geek', 'have', 'a', 'geeky', 'day']

s = 'prime'

res = np.any([s in i for i in l])

if res:

    print(f'{s} is present in the list')

else:

    print(f'{s} is not present in the list')

Output:
prime is not present in the list

Time complexity: O(nm), where n is the length of the input list and m is the length of the input string. The list comprehension has a time complexity of O(nm), as it iterates over each element of the list and checks if the string s is present in it.

Auxiliary Space: O(nm), where n is the length of the input list and m is the length of the input string. The list comprehension creates a new list of boolean values, which has a length of n, and each value in the list is a string of length m. Hence, the space complexity is O(nm).

  1. Use the for Loop to Find Elements From a List That Contain a Specific Substring in Python
  2. Use the filter() Function to Find Elements From a Python List Which Contain a Specific Substring
  3. Use the Regular Expressions to Find Elements From a Python List Which Contain a Specific Substring

Find String in List in Python

This tutorial will introduce how to find elements from a Python list that have a specific substring in them.

We will work with the following list and extract strings that have ack in them.

my_list = ['Jack', 'Mack', 'Jay', 'Mark']

Use the for Loop to Find Elements From a List That Contain a Specific Substring in Python

In this method, we iterate through the list and check whether the substring is present in a particular element or not. If the substring is present in the element, then we store it in the string. The following code shows how:

str_match = [s for s in my_list if "ack" in s]
print(str_match)

Output:

The in keyword checks whether the given string, "ack" in this example, is present in the string or not. It can also be replaced by the __contains__ method, which is a magic method of the string class. For example:

str_match = [s for s in my_list if s.__contains__("ack")]
print(str_match)

Output:

Use the filter() Function to Find Elements From a Python List Which Contain a Specific Substring

The filter() function retrieves a subset of the data from a given object with the help of a function. This method will use the lambda keyword to define the condition for filtering data. The lambda keyword creates a one-line lambda function in Python. See the following code snippet.

str_match = list(filter(lambda x: 'ack' in x, my_list))
print(str_match)

Output:

Use the Regular Expressions to Find Elements From a Python List Which Contain a Specific Substring

A regular expression is a sequence of characters that can act as a matching pattern to search for elements. To use regular expressions, we have to import the re module. In this method, we will use the for loop and the re.search() method, which is used to return an element that matches a specific pattern. The following code will explain how:

import re
pattern=re.compile(r'ack') 
str_match = [x for x in my_list if re.search('ack', x)]
print(str_match)

Output:

How To python find in string

This tutorial help to find python list item contains a string. I’ll walk you through the many circumstances for finding items in a Python list..

I have also shared How To Find Substring and Character into String. I’ve given an example utilizing the find() method, as well as the operator and index functions.

You can also checkout other python list tutorials:

  • Check Element Exist in List
  • How to Filter a List in Python
  • Python Join List Example
  • Python List Example And Methods
  • How To Compare Python Two Lists
  • How to Concatenate Two List in Python
  • How To Match String Item into List Python

How To First Match Element found

To find an element, I’ll utilize the python in operator. This aids in determining whether or not an element is present in the list of items.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456']
if any("test" in s for s in user_list):
 print("found");
else:
 print("not found")

The Result:

The above code will check a string is exist or not in the list.

Get All Matched Items in Python

Sometimes, We need to get all items which are containing the required substring. we’ll search substring into the python list and return all matched items that have substring.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matching = [s for s in user_list if "test" in s]
print(matching)
$python main.py
['samtest456', 'test123']

The above code’ll return all matched items from the source python list.

How To Match Against More Than One String

Let’s match more than one substring into the python list. We can combine two comprehensions and search into the list items.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matchers = ['test','adam']
matching = [s for s in user_list if any(xs in s for xs in matchers)]
print(matching);

The Results:

$python main.py
['adam789', 'samtest456', 'test123']

Python Filter To All Matched Items

The python filter is used to find all matching elements from the python list.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
matching = filter(lambda s: 'test' in s, user_list)
print(matching);

The Results:

$python main.py
['samtest456', 'test123']

Match Items Using Contains Private Method

You can also use the python contains method to find element exists or not into the python list. The __contains__() method of Pythons string class.

user_list = ['amar12', 'parvez34', 'adam789', 'samtest456', "test123"]
substr = "test"
for i in user_list:
    if i.__contains__(substr) :
        print(i, " is containing "+substr)

Results:

$python main.py
('samtest456', ' is containing test')
('test123', ' is containing test')

A similar solution using enumerate():

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

if word in word_list:
    for position, name in enumerate(word_list):
        if name == word:
            print("Your word is in the list at ", position)
else:
    print('Your word is not in the sentence')

You could also use a list comprehension:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

positions = [x for x, n in enumerate(word_list).split() if n == word]
if positions:
    for position in positions:
        print('your word is in the list at ', position)
else:
    print('Your word is not in the sentence')

Also, a generator expression that’s a little more efficient:

word, word_list = 'hello', 'hello what is your name i am bob this is a sentence a very n ice sentence'

found = False
for position in (x for x, n in enumerate(word_list) if n == word):
    print('your word is in the list at ', position)
    found = True
if not found:
    print('Your word is not in the sentence')

Понравилась статья? Поделить с друзьями:
  • Python find all word in string
  • Python excel ширина столбца
  • Python excel чтение столбца
  • Python excel чтение запись
  • Python excel цвет ячейки