Python在字符串中反向查找 [英] Python Reverse Find in String

查看:2763
本文介绍了Python在字符串中反向查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如:我想通过索引和<$ c $找到第二个索引c> str.rfind()

  s =您好,我是12!我喜欢浮游生物但我不喜欢棒球。 
index = 34#点到't'的'but'
index_of_2nd_I = s.rfind('I',index)
#returns = 36而不是16

现在我期望rfind()返回第二个I(16)的索引,但是返回36我发现rfind不支持反向查找。

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

解决方案

您的电话告诉rfind 开始寻找在索引34处。您希望使用 rfind重载需要一个字符串,一个开始和一个结束。告诉它从字符串开始( 0 )并停止看 index

 >>> s =你好,我12岁,我喜欢浮游生物,但我不喜欢棒球。 
>>> index = 34#到't'中的点'but'
>>> index_of_2nd_I = s.rfind('I',0,index)
>>>
>>> index_of_2nd_I
16


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?

解决方案

Your call told 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 at 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

这篇关于Python在字符串中反向查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆