Find a Text in a List in Python

This tutorial will discuss about unique ways to find a text in a list in Python.

Table Of Contents

Find index of String in Python List which contains the Text

Suppose we have a list which contains long string sentences, now we want to look for a text in this list. This text can be a substring in any of the string element of the list.

For this, we will use the enumerate() method to iterate over all the strings in the list, along with their index position. During iteration we will search for the text in the string, and if the string contains the text then we will mark its index position and break the loop. Once the fo-loop ends, we will have the index of string from list, which contains the given text.

Let’s see the complete example,

listObj = ['This story',
           'is about',
           'a small',
           'but very',
           'smart',
           'boy from a Country Village']

textStr = 'from'

idx = -1

# Enumerate over all strings in list along with index position
for index, strVal in enumerate(listObj):
    # check if text is present in this string from list
    if strVal.find(textStr) > -1:
        # mark the index of string which contains the text
        idx = index
        break

if idx > 0:
    print(f'Yes, Text "{textStr}" is present in the list item at index : {idx}')
else:
    print(f'No, Text "{textStr}" is not present in any string in list')

Output

Yes, Text "from" is present in the list item at index : 5

Find all indexes Strings in a Python List which contains the Text

In the previous example, we looked for the first occurrence of text in the list. If we want to locate all the instances or occurrences of text in the string, then we need to use the index() method multiple times in a loop. During each iteration, pass the start index as the index next to last returned index.

Let’s see the complete example,

listObj = ['This story',
           'is about',
           'a small',
           'but very',
           'smart',
           'boy, and he is from a Country Village']

textStr = 'is'

idxList = []

# Enumerate over all strings in list along with index position
for index, strVal in enumerate(listObj):
    # check if text is present in this string from list
    if strVal.find(textStr) > -1:
        # Add the index to a list
        idxList.append(index)

if idxList:
    print(f'Yes, Text "{textStr}" is present in the list item at indexes : {idxList}')
else:
    print(f'No, Text "{textStr}" is not present in any string in list')

Output

Yes, Text "is" is present in the list item at indexes : [0, 1, 5]

Summary

We learned, how to get the index of a text in a list in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top