How to Find the Highest Index of a Substring in Python

5/5 - (3 votes)

Problem Formulation and Solution Overview

At different times during your career as a Python Coder, you will encounter situations where you must determine the highest index of a substring occurrence. This article outlines various ways to accomplish this.


πŸ’¬ Question: How would we write code to find the highest index of a substring?

We can accomplish this task by one of the following options:


Method 1: Use String rfind()

This example uses the string.rfind() method, which returns a substring’s highest index (location) within a given string. If no match found, -1 returns.

This method accepts three (3) arguments, a substring, and a start and stop position. The only required argument is the substring.

If no start and stop positions are entered, it is assumed to be the start and end of the string, respectively. Therefore, the entire string will be searched for the occurrence of the stated substring.

phrase = 'think, Think, THINK'
found = phrase.rfind('think')
print(found)

Then, a string containing different variations of the word Think is declared and saved to the variable phrase.

Next, phrase is called, and rfind() is appended to phrase and passed one (1) argument, the substring to locate inside phrase. The results save to found and are output to the terminal.

What do you think found returns? If you said 0, you would be correct!

0

πŸ’‘Note: Based on the ASCII Table, lowercase and uppercase characters are assigned different values. Therefore, these three (3) versions of think, Think and THINK are different. The highest match is found at position 0.

Python String Methods [Ultimate Guide]

Method 2: Use regex finditer()

This example uses Python’s regex finditer() function to match a string pattern and returns an iterator containing non-overlapping matches.

import re

phrase = 'Think left, think right, think low, think high. The things you can think if you only try.'
found = [(i.start(), i.end(), i.group()) for i in re.finditer(r'think', phrase)]
print(found)

The above code imports Python’s built-in regex library, commonly referenced as re.

Then, a string containing a phrase is declared and saved to the variable phrase.

Next, List Comprehension is used with finditer() to locate matches and record their start and stop positions in the string phrase. If output to the terminal, the following would display.

[(12, 17, 'think'), (25, 30, 'think'), (36, 41, 'think'), (67, 72, 'think')]

To retrieve the highest value, slicing is used as follows.

found = [(i.start(), i.end(), i.group()) for i in re.finditer(r'think', phrase)]
print(found[-1])
# (67, 72, 'think')

Method 3: Use String rindex()

This example uses regex rindex() to find the Highest Index of a substring and returns a match object if found. A ValueError returns if no match is found.

phrase = 'think, think, THINK'
found = phrase.rindex('think')
print(found)
# 7

A string is declared and saved to the variable phrase.

Next, the rindex() method is declared and passed one (1) argument, the substring to search for ('think'). The output saves to found and is output to the terminal.


Method 4: Use more_itertools.relocate()

This example uses the more_itertools.relocate() function to locate the highest occurrence of a character in a string and returns the position. If not found, -1 returns.

Before moving forward, please ensure the more_itertools library is installed. Click here if you require instructions.

import more_itertools

phrase = 'the cat in the hat'
search_char = 't'
found = next(more_itertools.rlocate(phrase, lambda x: x == search_char))
print(found)

The above code imports the more_itertools library which offers elegant solutions for creating iterables.

Then, a string is declared, and saves to phrase. In addition, a search character is declared and saves to search_char.

Next, more_itertools is used in conjunction with a lambda to locate the last occurrence of the search_char in phrase. The results save to found and output to the terminal.

17
Let's Play Finxter - The Lambda Function in Python

Summary

This article has provided five (5) ways to find the highest index of a substring to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programming Humor

πŸ’‘ Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.

~~~

  • Question: Why do Java programmers wear glasses?
  • Answer: Because they cannot C# …!

Feel free to check out our blog article with more coding jokes. πŸ˜‰