2010-08-21 683 views
21

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

举个例子:我想用食指和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()返回第二个我的(16)索引找到第二个我的指标,但它返回36.在查看文档后,我发现rfind不支持反向查找。

我对Python完全陌生,所以有内置解决方案来反向查找?就像用一些python [:: - 1]魔法反转字符串并使用find等一样?或者我将不得不通过字符串来反转char字符?

+1

如果jsz真的是12那么他/她是一个明亮的孩子;-) – sidewinderguy 2011-05-25 02:14:40

+0

是的,反向查找的开始不是最右边的项目。我发现(在双关语意图中)'rfind'中的'r'具有误导性。将's.rfind(s,start,end)'作为's [start:end]'返回* last *出现的含义并不明确。 – YvesgereY 2016-02-28 21:03:53

回答

27

您的电话号码告诉rdind 开始寻找索引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 
0

我开始好奇如何实现找N次从rpartition结束的字符串,这样做,第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) 
+1

哇,真的很痛:( – unbeli 2010-08-21 20:39:11

+0

具体是什么?动机是,不像发现分区没有起始索引,因为它是无索引的。 – 2010-08-21 21:07:50