Python 字符串反向查找

54 投票
3 回答
126483 浏览
提问于 2025-04-16 03:07

我有一个字符串和一个字符串中的任意索引。我想在这个索引之前找到一个子字符串第一次出现的位置。

举个例子:我想通过这个索引来找到第二个字母"I"的位置,使用的是str.rfind()这个方法。

s = "Hello, I am 12! I like plankton but I don't like Baseball."
index = 34 #points to the 't' in 'but'
index_of_2nd_I = s.rfind('I', index)
#returns = 36 and not 16 

现在我本来期待rfind()能返回第二个"I"的位置(16),但它却返回了36。查阅文档后我发现,rfind并不是代表反向查找。

我对Python完全是新手,请问有没有内置的方法可以进行反向查找?比如用一些Python的魔法,比如[:: -1]来反转字符串,然后再用find,等等?还是说我得一个字符一个字符地反向遍历这个字符串呢?

3 个回答

1

要找到第二个'I'的位置:
s.find('I', s.find('I')+1) # 返回16

找到最后一个'I'的位置:
s.rfind('I') # 返回36

找到所有'I'出现的位置:
locs = [idx for idx,ltr in enumerate(s) if ltr == 'I'] # [7, 16, 36]

2

我对如何使用 rpartition 从字符串的末尾查找 n 次产生了好奇,于是我做了这个 nth rpartition 循环:

orig = s = "Hello, I am 12! I like plankton but I don't like Baseball."
found = tail = ''
nthlast = 2
lookfor = 'I'
for i in range(nthlast):
    tail = found+tail
    s,found,end = s.rpartition(lookfor)
    if not found:
        print "Only %i (less than %i) %r in \n%r" % (i, nthlast, lookfor, orig)
        break
    tail = end + tail
else:
    print(s,found,tail)
66

你让 rfind 从索引34开始查找。你想使用一个可以接受字符串、起始位置和结束位置的 rfind重载。告诉它从字符串的开头(0)开始查找,并在 index 这个位置停止。

>>> s = "Hello, I am 12! I like plankton but I don't like Baseball."
>>> index = 34 #points to the 't' in 'but'
>>> index_of_2nd_I = s.rfind('I', 0, index)
>>>
>>> index_of_2nd_I
16

撰写回答