2010-08-21 682 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