查找字符串中最后出现的子字符串的索引

问题:查找字符串中最后出现的子字符串的索引

我想在给定的输入string中找到某个子字符串最后一次出现的位置(或索引)str

例如,假设输入字符串为str = 'hello',子字符串为target = 'l',则它应输出3。

我怎样才能做到这一点?

I want to find the position (or index) of the last occurrence of a certain substring in given input string str.

For example, suppose the input string is str = 'hello' and the substring is target = 'l', then it should output 3.

How can I do this?


回答 0

用途.rfind()

>>> s = 'hello'
>>> s.rfind('l')
3

另外,请勿将其str用作变量名,否则将使内置的阴影变暗str()

Use .rfind():

>>> s = 'hello'
>>> s.rfind('l')
3

Also don’t use str as variable name or you’ll shadow the built-in str().


回答 1

您可以使用rfind()Python2链接:rindex()
rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

区别在于未找到子字符串时rfind()返回,-1rindex()引发异常ValueError(Python2链接:)ValueError

如果您不想检查rfind()返回码-1,则可能会希望rindex()提供一个可理解的错误消息。否则,您可能会搜索分钟,其中意外值-1来自您的代码…


示例:搜索最后一个换行符

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

You can use rfind() or rindex()
Python2 links: rfind() rindex()

>>> s = 'Hello StackOverflow Hi everybody'

>>> print( s.rfind('H') )
20

>>> print( s.rindex('H') )
20

>>> print( s.rfind('other') )
-1

>>> print( s.rindex('other') )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).

If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code…


Example: Search of last newline character

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

回答 2

使用str.rindex方法。

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

Use the str.rindex method.

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

回答 3

尝试这个:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

Try this:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

回答 4

more_itertools库提供了用于查找所有字符或所有子字符串的索引的工具

给定

import more_itertools as mit


s = "hello"
pred = lambda x: x == "l"

性格

现在有rlocate可用的工具:

next(mit.rlocate(s, pred))
# 3

补充工具是locate

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3

子串

还有一个window_size参数可用于查找多个项目的前导项目:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

The more_itertools library offers tools for finding indices of all characters or all substrings.

Given

import more_itertools as mit


s = "hello"
pred = lambda x: x == "l"

Code

Characters

Now there is the rlocate tool available:

next(mit.rlocate(s, pred))
# 3

A complementary tool is locate:

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3

Substrings

There is also a window_size parameter available for locating the leading item of several items:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

回答 5

尚未尝试恢复无效的帖子,但是由于尚未发布…

(这是我在发现此问题之前的做法)

s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)

说明:当您搜索最后一个匹配项时,实际上是在搜索反向字符串中的第一个匹配项。知道了这一点,我做了s[::-1](返回一个反向字符串),然后target从那里索引了。然后我这样做len(s) - 1 - the index found是因为我们希望索引不被反转(即原始)字符串中建立。

不过要当心!如果target超过一个字符,则可能无法在反向字符串中找到它。要解决此问题,请使用last_pos = len(s) - 1 - s[::-1].index(target[::-1]),它会搜索的反向版本target

Not trying to resurrect an inactive post, but since this hasn’t been posted yet…

(This is how I did it before finding this question)

s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)

Explanation: When you’re searching for the last occurrence, really you’re searching for the first occurrence in the reversed string. Knowing this, I did s[::-1] (which returns a reversed string), and then indexed the target from there. Then I did len(s) - 1 - the index found because we want the index in the unreversed (i.e. original) string.

Watch out, though! If target is more than one character, you probably won’t find it in the reversed string. To fix this, use last_pos = len(s) - 1 - s[::-1].index(target[::-1]), which searches for a reversed version of target.


回答 6

如果您不想使用rfind,则可以解决问题/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

If you don’t wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

回答 7

您可以使用rindex()函数获取字符串中字符的最后一次出现

s="hellloooloo"
b='l'
print(s.rindex(b))

you can use rindex() function to get the last occurrence of a character in string

s="hellloooloo"
b='l'
print(s.rindex(b))