如何利用python找到一个子串的最高索引

125 阅读3分钟

问题的提出和解决方案概述

在你作为Python程序员的职业生涯中的不同时期,你会遇到必须确定一个子串出现的最高索引的情况。这篇文章概述了完成这一任务的各种方法。


💬 问题:我们如何编写代码来寻找一个子串的最高索引?

我们可以通过以下方法之一来完成这项任务。

  • 方法1 :使用 string.rfind()
  • 方法2 :使用 regexfinditer()
  • 方法3 :使用 regexrindex()
  • 方法4:使用 [more_itertools.rlocate()](https://blog.finxter.com/fixed-modulenotfounderror-no-module-named-more-itertools/)

方法1:使用字符串rfind()

这个例子使用了 string.rfind()方法,它返回子串在给定字符串中的最高索引(位置)。如果没有找到匹配,则返回-1

这个方法接受三(3)个参数,一个子串,以及一个开始和停止位置。唯一需要的参数是子串。

如果没有输入开始和停止的位置,就会分别假定为字符串的开始和结束。因此,整个字符串将被搜索,以寻找所述子字符串的出现。

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

然后,声明一个包含单词Think 的不同变化的字符串,并保存到变量phrase

接下来,调用phrase ,并且 rfind()被附加到phrase ,并传递一个(1)参数,即要在phrase 中定位的子串。结果保存到found ,并输出到终端。

你认为什么是 `found`返回什么?如果你说是0,那么你是正确的!

0

💡注意:根据ASCII表,小写字母和大写字母被赋予不同的值。因此,这三(3)个版本的thinkThinkTHINK是不同的。匹配度最高的是在第0位找到的。


方法2:使用regex finditer()

这个例子使用Python的 [regex](https://blog.finxter.com/python-regex/)finditer()函数来匹配一个字符串模式,并返回一个包含非重叠匹配的迭代器

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)

上面的代码导入了Python的内置 [regex](https://blog.finxter.com/python-regex/)库,通常被称为re

然后,声明一个包含短语的字符串并保存到变量phrase

接下来,List Comprehensionfinditer()来定位匹配,并记录它们在字符串中的开始和停止位置phrase 。如果输出到终端,将显示如下。

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

为了检索最高值,使用切片法,如下所示。

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

方法3:使用字符串rindex()

这个例子使用了 regexrindex()来查找一个子串的最高索引,如果找到了,则返回一个匹配对象。A ValueError如果没有找到匹配对象则返回。

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

声明一个字符串并保存到变量phrase

接下来,该 rindex()方法被声明并通过一个(1)参数,即要搜索的子串('think')。输出结果保存到found ,并输出到终端。


方法4:使用more_itertools.relocate()

这个例子使用more_itertools.relocate() 函数来定位一个字符串中出现次数最多的字符,并返回该位置。如果没有找到,-1 返回。

在继续前进之前,请确保已经安装了more_itertools 库。

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)

上面的代码导入了 [more_itertools](https://blog.finxter.com/fixed-modulenotfounderror-no-module-named-more-itertools/) 库,它为创建迭代表提供了优雅的解决方案。

然后,声明一个字符串,并保存到phrase 。此外,声明一个搜索字符,并保存到search_char

下一步。 [more_itertools](https://blog.finxter.com/fixed-modulenotfounderror-no-module-named-more-itertools/)与一个lambda结合使用,以定位短语中最后出现的search_char 。结果保存到found ,并输出到终端。

17

摘要

本文提供了(4)种寻找子串最高索引的方法,以选择最适合你的编码要求。

祝您好运,编码愉快!