Python反向查找字符串

时间:2010-08-21 12:59:09

标签: python string find reverse

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

一个例子:我想通过使用索引和str.rfind()找到第二个I的索引

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等?或者我是否必须通过字符串反复迭代char?

2 个答案:

答案 0 :(得分:40)

你的电话告诉rfind 在索引34处开始寻找。你想使用带有字符串,开头和结尾的rfind overload。告诉它从字符串的开头(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

答案 1 :(得分:2)

我很好奇如何通过rpartition实现n次查找字符串并执行此第n个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)