×

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 program to display ASCII value of the character

Python program to display ASCII value of the character The full form of ASCII is American Standard Code for Information Interchange. This example explains a program in Python to find the...

1 minute read.

Isodate Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

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.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Count Number of Keys in Dictionary Python

Dictionary is a particular data type in python. Dictionary stores unique values by taking different keys and their assigned values. Through this article, we will learn about python dictionary count,...

3 minutes read.

Python Pascal Triangle

Python Pascal Triangle Pascal triangle A pascal triangle is a number pattern of triangular array of the binomial coefficients. For designing a pascal triangle, we write a function in the program which...

5 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Python program to perform the arithmetic operation

Python program to perform the arithmetic operation This program will write a code to perform some basic arithmetic operations like addition, subtraction, multiplication, exponent, modulus, and division. Here we first need...

2 minutes read.

Python Euclidean Distance

Euclidean distance is the distance between two points with whatever of dimensions. We are using NumPy library to find and calculate the Euclidean distance. The NumPy library is used for...

1 minute read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

Python Typing Module

An Introduction to the Typing Module The typing module is introduced in Python version 3.5 and used to provide hinting method types in order to support static type checkers and linters...

10 minutes read.

Python slice()

Python slice() class The slice() class return a slice object representing the set of indices specified by range(start, stop, step).  Syntax class slice(stop)          or class slice(start, stop[, step]) Parameter Start: This parameter represents an integer number specifying at...

1 minute read.