All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Find All Occurrences Of A Substring In A String Python

Last Updated : Mar 11, 2024

Find All Occurrences Of A Substring In A String Python

In this article we will show you the solution of find all occurrences of a substring in a string pythons, let's examine the idea of a Python function that finds every instance of a substring within a string.

An uninterrupted run of characters inside a String is known as a substring. For instance, Locate a substring inside a text is just a substring of substring.

One of the most popular types of data to record data in a way that is understandable by humans is a string, which in Python is an array of bytes that represent Unicode characters.

Now let's talk about the Python idea of finding every instance of a substring within a string.

Step By Step Guide On Find All Occurrences Of A Substring In A String Pythons :-

We frequently run into issues when dealing with substrings when working with strings.

This may involve trying to locate a specific substring in all of its locations in a string.

In order to iterate through the entire target string, list comprehension is employed, with the startswith function serving largely as a tool for obtaining the beginning indices of substrings.

Method - Using string slicing and while loop

def find_all_substrings(string, substring):
 indices = []
 i = 0
 while i < len(string):
  j = string.find(substring, i)
  if j == -1:
   break
  indices.append(j)
  i = j + len(substring)
 return indices
test_str = "Talkerscode is best for Learners"
test_sub = "Learners"
print(find_all_substrings(test_str, test_sub))
  1. You can see that we used a while loop and string slicing to create the Python programme in this example.
  2. We disobey the function that attempts to extract all substrings from string at the beginning of the code.
  3. Next, we initialise a list that is empty and will be used to record the indices of every instance of the substring.
  4. The initial index I must then be set to 0.
  5. After that, a while loop is used to keep looking through the string for the substring.
  6. Just use find() method within the while loop to locate the first instance of the substring with in string, starting at the current index i.
  7. Then if find() returns -1, it means that there are no more occurrences of the substring in the string, so break out of the loop.
  8. After that if find() returns a non-negative value, append the index of the first character of the substring to the list, and update the starting index i to the next character after the end of the substring.
  9. Continue using the find function until the string contains no more instances of the substring.
  10. In the last we use print function for returning the list of indices.

Method - a substring using startswith()

string1="""Python programming language. Python is object-oriented,
Python supports database connectivity and Python supports
List,set, tuple and dictionary"""
indices = [i for i in range(len(string1)) if string1.startswith("supports", i)]
print(indices)
num = len([i for i in range(len(string1)) if string1.startswith("supports", i)])
print(num)
  1. A starting indexes of the substring "supports" will be obtained in this example, and we'll then return the overall frequency.
  2. The string is used to write certain statements at the beginning of the code.
  3. So, in order to obtain all indexpositions where the substring is supported and the iterator reflects the position, the string must first exist.
  4. A certain substring's starting index can be obtained using the startswith() method. If we want to get all of the occurrence indices back.
  5. Next, to print those indices, we utilise the print function in Python.
  6. Next, using the len function, we obtain the overall number of instances of supports.
  7. The len() method can then be applied to it to return the overall number of occurrences.
  8. To print the number of occurrences, we then utilise the print function once again.
  9. We can see that the string contained two instances of supports and that beginning indexes were also returned.

Conclusion :-

As a result, we have learned valuable how to use Python to find every instance of such a substring inside a string.

We also discovered that list comprehension is used to loop through the full target string, the with startswith function mostly being used to acquire the beginning indexes of substrings.

I hope this article on find all occurrences of a substring in a string python helps you and the steps and method mentioned above are easy to follow and implement.