×

Python Ways to find nth occurrence of substring in a string

Introduction

In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part of some other string.

We will examine various methods to discover the n - th position of the substring with Python and retrieve the index in which the substring appears just after nth occurrence.

We perform the operations to find the nth occurrences of a substring by using the below said methods. They are

  1. find() method
  2. split() method
  3. Using regular expression

1. find()

To locate the position of the very first appearance of the given value in Python, use the find() function. The find() function also allows us to define a beginning and a finishing index. We are instructed to confine our search to the given range by using these starting and finishing indexes. We used the find() method on the string, which will in each iteration locate the first instance of the substring throughout our input sequence.

Code

# example python program for finding the nth 
# occurrences of a substring in the string Using
# find() method


# declare string
string = "itcseitcseitcseece"
# give the substring
str = "cse"
# iterated times is
n = 2
# declare output var as -1
output = -1
# implement for loop
for i in range(0, n):
    output = string.find(str,output+1)
# print the result
print ("The Nth occurrence of the substring is ", c)

Output

The Nth occurrence of the substring is  7

Due to the output value being originally set to -1 in our code's find() function, the entire string will indeed be examined from the 0th index to a conclusion in the first iteration. We will get the first instance of the split in our initial string from this iteration. The string will be searched from index 1 to the end mostly on second iteration, though. We will get the second appearance of our substring from this iteration. To find the nth instance of the string, we can perform such n repetitions.

2. split()

The provided text can be divided into such a collection of strings using a defined separator using the split() function in Python. Where the string needs to be broken, however, the separator (flat screen) can be specifically specified. Maxsplit, a secondary parameter that would be an argument towards the split() function, is used to determine how many repetitions the string must be split when a substring is discovered.

Code

# example python program for finding the nth 
# occurrences of a substring in the string Using
# split() method
def solve(string, s, n):
    div = string.split(s, n)
    if len(div) <= n:
        return -1
    return len(string) - len(div[-1]) - len(s)
# print the result
print(solve('friend theend endeavour bend', 'end', 4))

Output

25

In the programme above, there is a function called solution() whose core logic is carried out. When substring s is supplied as a separator and indeed the amount of n is provided as the result of maxsplit in the initial line's application of the split() method. The indexes where we locate our substring s are where the original string is divided. Nevertheless, due to the value of n, this split only occurs twice. That at a certain index, the last string kept in the div variable equals our substring, although we haven't split them.

Following the split() method, we tested a condition to see if the length of the div variable exceeded the value of n. If this was the case, we would need to return -1 because the user might be trying to find the nth instance of a substring that doesn't exist n times. As we have only divided the string n times, our basic logic now determines the index of the substring's nth occurrence. As a result, the final element of the div variable is stored as the string that may have remained after the nth instance of the substring.

As a result, we divide the length from the last string inside the div variable, which can be accessed as div[-1], by the length of the previous string string. Since we also need to have the beginning index, we will deduct the substring length from this value, which gives the index where its recurrence of our targeted substring ends. This will enable us to determine the index of the nth instance of a substring.

3. Regular Expression

A series of characters can be used to create a search pattern when using regular expressions to discover a certain pattern in a string. The re module for regular expressions is available in Python. For locating the nth instance of the substring, we'll use the re package.

Code

# example python program for finding the nth 
# occurrences of a substring in the string Using
# regular expression


# import regular expression
import re
# instantiate any string
string = "hiiamhiiam"
# give number of iterations
n = 2
output = [x.start() for x in re.finditer(r"hi" , string)]
if(len(output)<=n):
# print the result
    print(output[n-1])

Output

5

To be using regular expressions inside the program above, we installed the re library in the very first line. The input has then been defined after that. All or most of the substring's beginning indexes are located using the for loop, and they are then saved in the outcome variable. Therefore, because we verify the relationship between the time of the results page and the n variable, if the user inputs a number for n that wasn't in the string, a warning will be raised.

We employ the finditer() procedure from the re package, which provides us with the starting and stopping indexes of every substring that matches the main string, but we only require the beginning index to locate the nth instance. As a result, we employ the x.start() operation, which only returns the commencing indexes of the selected substring. The nth instance of the substring is printed after our index.


Related Topics

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Creating Tables using Python MySQL

In this article, we are going to learn how to create tables in databases using Python MySQL. Introduction to Tables: Generally, databases are used in order to store the information in the...

9 minutes read.

Read JSON File in Python

JSON refers to the JavaScript Object Notation. It is a Data format used for representing structured data and it is used to transfer and store data. In JSON format, the...

5 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python program to count and display vowels in a string

Python program to count and display vowels in a string This python program counts the vowels in a string and displays them on the screen. We can do this in several...

2 minutes read.

Python Compiler

What is Compiler? The compiler is mainly a program used to convert the source code into the machine or binary code. The source code is generally a computer program written using...

6 minutes read.

Python Logging Maxbytes

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python Set add() Method

Python Set add() Method The set.add() method adds the specified element to a set. If the element is already present in the set, it doesn't add it. Syntax set.add(element) Parameter element- This parameter represents the element that...

1 minute read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Multiple Linear Regression using Python

Linear Regression: Linear regression is a method that models the relationship between a dependent variable and one or more independent variables; in other terms, that models the relationship between a target...

6 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

How To Take Multiple Inputs In Python

In C language, we make use of the scanf() function to obtain the values from the user and store it in the variable. Coming to the Python language, we use the...

5 minutes read.

Python Set Methods

[et_pb_section][et_pb_row][et_pb_column type="4_4"][et_pb_text] Python Set Methods A set is a collection which is unordered and unindexed. Python has a set of built-in methods that you can use on sets. Methods ...

4 minutes read.

Python program to sort the array element into ascending order

Python program to sort the array element into ascending order In this example, we'll see how to sort the array elements in ascending order using a Python program. Sorting is a...

2 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Creating new Database using Python MySQL

In this article, we are going to discuss how to create a new database by connecting Python and MySQL. What is a Database? The places or memory used to secure highly and...

6 minutes read.