Python program to find the occurrence of substring in the string
Last Updated :
21 Apr, 2023
Given a list of words, extract all the indices where those words occur in the string.
Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"]
Output : [2, 4]
Explanation : best and geeks occur at 2nd and 4th index respectively.
Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks", "is"]
Output : [1, 2, 4]
Explanation : is, best and geeks occur at 1st, 2nd and 4th index respectively.
Method #1 : Using list comprehension + split() + index()
In this, we perform the task of getting words from sentences using split(), and then match words from the string list to extracted strings using index().
Python3
# Python3 code to demonstrate working of
# Word occurrence positions in String
# Using list comprehension + split() + index()
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing list
test_list = ["best", "geeks", "cs"]
# using index() to get indices,
# list comprehension used to offer one liner
res = [test_str.split().index(ele)
for ele in test_str.split() if ele in test_list]
# printing result
print("The indices list : " + str(res))
OutputThe original string is : geeksforgeeks is best for geeks and cs
The indices list : [2, 4, 6]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + enumerate() + split()
This is yet another way in which this task can be performed. In this task of getting indices is done using enumerate().
Python3
# Python3 code to demonstrate working of
# Word occurrence positions in String
# Using list comprehension + enumerate() + split()
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# printing original string
print("The original string is : " + str(test_str))
# initializing list
test_list = ["best", "geeks", "cs"]
# using enumerate() to get indices,
# list comprehension used to offer one liner
res = [idx for idx, ele in enumerate(test_str.split()) if ele in test_list]
# printing result
print("The indices list : " + str(res))
OutputThe original string is : geeksforgeeks is best for geeks and cs
The indices list : [2, 4, 6]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 3: The idea is to use a simple for loop to iterate through each word in the string and check if it is present in the given list of words
Steps:
- Initialize a string test_str with some sample text.
- Create a list test_list of words whose positions we want to find in the string.
- Create an empty list res to store the positions of the words in the string.
- Use the split() method to split the string into a list of words, so that we can iterate over each word.
- Use a for loop to iterate through each word in the string, along with its index.
- Check if the current word is present in the test_list using the in operator.
- If the word is present in the list, append its index to the res list.
- Print the final list of indices.
Python3
# initializing string
test_str = 'geeksforgeeks is best for geeks and cs'
# initializing list
test_list = ["best", "geeks", "cs"]
# initializing an empty list to store the indices
res = []
# iterating through each word in the string
for idx, word in enumerate(test_str.split()):
# checking if the word is in the given list
if word in test_list:
# appending the index of the
# word to the result list
res.append(idx)
# printing the result list
print("The indices list : " + str(res))
OutputThe indices list : [2, 4, 6]
Time Complexity: O(n), where n is the number of words in the string.
Auxiliary Space: O(k), where k is the number of occurrences of the words in the given list in the string.
Similar Reads
Python | Ways to find nth occurrence of substring in a string Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.findit
4 min read
Python - All occurrences of Substring from the list of strings Given a list of strings and a list of substring. The task is to extract all the occurrences of a substring from the list of strings. Examples: Input : test_list = ["gfg is best", "gfg is good for CS", "gfg is recommended for CS"] subs_list = ["gfg", "CS"] Output : ['gfg is good for CS', 'gfg is reco
5 min read
Python | Get the string after occurrence of given substring The problem involves getting the string that is occurring after the substring has been found. Let's discuss certain ways in which this task can be performed using Python.Using partition()To extract the portion of a string that occurs after a specific substring partition() method is an efficient and
3 min read
Python - All occurrences of substring in string A substring is a contiguous occurrence of characters within a string. Identifying all instances of a substring is important for verifying various tasks. In this article, we will check all occurrences of a substring in String.Using re.finditer()re.finditer() returns an iterator yielding match objects
3 min read
Python | Get the starting index for all occurrences of given substring Given a string and a substring, the task is to find out the starting index for all the occurrences of a given substring in a string. Let's discuss a few methods to solve the given task. Method #1: Using Naive Method Python3 # Python3 code to demonstrate # to find all occurrences of substring in # a
3 min read
Python Program To Check If A String Is Substring Of Another Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :Â Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
3 min read
Get Second Occurrence of Substring in Python String We are given a string and a substring, and our task is to find the index of the second occurrence of that substring within the string. This means we need to identify not just if the substring exists, but where it appears for the second time. For example, if we have a string like "hello world, hello
2 min read
Python Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
6 min read
Count Occurance of Substring in a List of Strings - Python To count the occurrences of a particular substring in a list of strings in Python, we can use several methods. In this article, we are going to explore different methods to count the existence of a particular substring in a given list.Using sum() and Generator ExpressionThis method uses a generator
2 min read
Python | Find last occurrence of substring Sometimes, while working with strings, we need to find if a substring exists in the string. This problem is quite common and its solution has been discussed many times before. The variation of getting the last occurrence of the string is discussed here. Let's discuss certain ways in which we can fin
8 min read