Python 在字符串中反向查找
我有一个字符串和该字符串的任意索引。我想找到索引之前第一次出现的子字符串。
一个例子:我想通过使用索引和 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 等?或者我是否必须通过字符串反向迭代一个字符?
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()
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的调用告诉 rfind 开始查找索引 34。您想要使用 rfind 重载,它需要一个字符串、一个开始和一个结束。告诉它从字符串的开头 (
0
) 开始,并停止查看index
:Your call tell
rfind
to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0
) and stop looking atindex
:我很好奇如何实现通过 rpartition 从末尾查找字符串 n 次,并执行了第 n 个 rpartition 循环:
I became curious how to implement looking n times for string from end by rpartition and did this nth rpartition loop:
寻找第二个“我”:
s.find('I', s.find('I')+1) # returns 16
查找最后一个 'I':
s.rfind('I') # returns 36
查找所有 'I' 出现的下标:
locs = [idx for idx,ltr in enumerate(s) if ltr == 'I'] # [7, 16, 36]
To find the 2nd 'I':
s.find('I', s.find('I')+1) # returns 16
Find the last 'I':
s.rfind('I') # returns 36
Find the indeces of all 'I' occurrences:
locs = [idx for idx,ltr in enumerate(s) if ltr == 'I'] # [7, 16, 36]