×

Find Last Occurrence of Substring using Python

Introduction

When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to solve it. Here, it is discussed how to obtain the string's most recent occurrence. Let's talk about a few approaches to use Python to locate the final instance of a substring within a string.

String

A string can be defined as the collecting of characters that can represent a single word or an entire sentence. Python allows us to declare strings and other datatypes without using the datatype constant. Consequently, using strings in Python is simpler than using them in other programming languages.

An entity of said String class, which has numerous methods for manipulating and gaining access to strings, is a string.

Apply rindex() Technique

Using the rindex() method from the built-in Python String class is one technique to determine the index of the final instance of a substring. It takes a string encoding the desired substring as an argument and returns the position of that string's last occurrence in the current string.

This function's primary flaw has been that it raises an exception because the string contains no substrings.

Code

# example python code to find
# the substring’s last occurence
# the last occurrence of substring
# with the help of rindex() method


# declare any example string
string = 'The trees outside my window are green and full of leave'


# declare any word from the string
word = " green "


# with the help of rindex() find 
# the last occurrence of the substring
x = string.rindex(word)


# displaying the initialized string
print(' The string is = ' + str(string))


# displaying the index value
print(' Required index of the substring is = ' + str(x))

Output

The string is = The trees outside my window are green and full of leave
Required index of the substring is = 32

Applythe rfind() Technique

There is yet another method called rfind that can be used to get around rindex(). Its behaviour is comparable to that of rindex(), but instead of throwing an error if the requested substring is not found in the string, this technique produces "1," showing that it is just not.

One can specify the starting index from which you would really like to start as well as the end index as alternative options for both rfind() & rindex().

Code

# example python code to find
# the substring’s last occurence
# with the help of rfind() method


# declare any example string
string = 'He is a good student'


# declare any word from the string
word = "is"


# with the help of rfind() find 
# the last occurrence of the substring
x = string.rfind(word)


# displaying the initialized string
print(' The string is = ' + str(string))


# displaying the index value
print(' Required index of the substring is = ' + str(x))

Output

The string is = He is a good student
Required index of the substring is = 3

In [5]:

Use Techniques find() and replace()

Code

# example python code to find
# the substring’s last occurence
# with the help of find() and replace()


# declare any example string
string = 'The cat is sleeping on the pillow'


# declare any word from the string
word = "pillow"


# using find() and replace()
var = string.count(word)
i=1
while(i<var):
	string=string.replace(word,"*"*len(word),1)
	i= i+1
x=string.find(word)
# displaying the initialized string
print(' The string is = ' + str(string))


# displaying the index
print(' Required index of the substring is = ' + str(x))

Output

The string is = The cat is sleeping on the pillow
Required index of the substring is = 27

Combine rlocate() Method with lambda()

Now, we are utilising the rlocate() method of the more itertools package, which enables us to pinpoint the substring's final occurrence within the input string.

Code

# importing the module
import more_itertools as mi


# declare any example string
string = 'My favorite color is blue'


# declare any word from the string
word = "color"


#  using lambda
pred = lambda *var: var == tuple(word)
# using rlocate() 
x = next(mi.rlocate(string, pred=pred,window_size=len(word)))
# displaying the initialized string
print(' The string is = ' + str(string))


# displaying the index
print(' Required index of the substring is = ' + str(x))

Output

The string is = My favorite color is blue
Required index of the substring is = 12

Related Topics

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

What is Python online compiler?

The compiler is a program that is used to scan an entire high-level program (source code) and it translates the scanned program into machine code. Compilers convert .py source code into...

5 minutes read.

Python Web Development projects

What is Python? Python is currently one of the most widely used computer programming languages. This isn't just an exaggeration; Python is the second-most famous programming language on the software development...

3 minutes read.

CSV Write in Python

What is meant by CSV? CSV stands for Comma Separated Values. The name itself defines its purpose. CSV arranges the data in the form of tables and stores the organized data in...

3 minutes read.

Python String isupper() method

Python String isupper() method The String.isupper() method in Python returns a boolean value ‘true’ if all cased characters in the string are uppercase else for any other value is returns false. Syntax String.isupper() Parameter NA Return This...

2 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Difference between For Loop and While Loop in Python

What is the “For” loop? The “For” Loop is a commonly used control structure in programming that allows us to repeat a set of actions multiple times. The “For” loop is...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands....

5 minutes read.

Python And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python Read Excel file

Python Read Excel file Excel is the spreadsheet application for Window, which is developed by Microsoft. The Excel stores data in the tabular form. It provides easy access to analyze and maintain the...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.