Python 在字符串中反向查找

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3537717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:37:40  来源:igfitidea点击:

Python Reverse Find in String

pythonstringfindreverse

提问by

I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index.

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

An example: I want to find the index of the 2nd I by using the index and str.rfind()

一个例子:我想通过使用索引找到第二个 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 

Now I would expect rfind() to return the index of the 2nd I (16) but it returns 36. after looking it up in the docs I found out rfind does not stand for reverse find.

现在我希望 rfind() 返回第二个 I (16) 的索引,但它返回 36。在文档中查找后我发现 rfind 不代表反向查找。

I'm totally new to Python so is there a built in solution to reverse find? Like reversing the string with some python [::-1] magic and using find, etc? Or will I have to reverse iterate char by char through the string?

我对 Python 完全陌生,所以是否有内置的反向查找解决方案?喜欢用一些 python [::-1] 魔法反转字符串并使用 find 等?或者我是否必须通过字符串一个字符一个字符地反向迭代?

采纳答案by Blair Conrad

Your call tell rfind to start lookingat index 34. You want to use the rfind overloadthat takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:

您的调用告诉 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

回答by Tony Veijalainen

I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop:

我开始好奇如何通过 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)