Python 在索引之前查找子字符串的第一个匹配项
是否有类似于myStr.find(subStr,startInd)的方法来获取Python 在索引之前查找子字符串的第一个匹配项,python,string,python-3.x,find,substring,Python,String,Python 3.x,Find,Substring,是否有类似于myStr.find(subStr,startInd)的方法来获取subStr在mystartInd之前第一次出现的索引。是否要从开始执行步骤-1而不是1 编辑 这里有一个例子: myStr = "(I am a (cool) str)" startInd = 9 # print(myStr[startInd]) -> "c" print(myStr.find(")", startInd)) # -> 13 print(myStr.findBefore("(",
subStr
在mystartInd
之前第一次出现的索引。是否要从开始执行步骤-1而不是1
编辑
这里有一个例子:
myStr = "(I am a (cool) str)"
startInd = 9 # print(myStr[startInd]) -> "c"
print(myStr.find(")", startInd)) # -> 13
print(myStr.findBefore("(", startInd)) # -> 8
编辑II
下面的代码解决了我的问题,但不是很方便。想问一下是否有一个简单的方法来完成这项任务
startInd = 9
myStr = "(I am a (cool) str)"
print(myStr.find(")", startInd)) # -> 13
print(len(myStr[::-1]) - myStr[::-1].find("(", len(myStr[::-1]) - startInd - 1) - 1) # -> 8
采用可选的end
参数:
str.find(sub[,start[,end]])
返回在切片s[start:end]中找到子字符串sub的字符串中的最低索引。可选参数start和end是
解释为切片表示法
因此,如果希望subStr
在endIndex
之前结束,可以使用myStr.find(subStr,0,endIndex)
:
如果希望subStr
在endIndex
之前的任何位置开始,则必须使用myStr.find(subStr,0,endIndex+len(subStr))
:
>>> 'hello world'.find('ello', 0, 1 + len('ello'))
1
>>> 'hello world'.find('ello', 0, 0 + len('ello')) # it starts at index 1, so it's not found
-1
你只是在找吗?@abarnert不完全是。我在问题中加了一个例子,使我的意思更清楚。
>>> 'hello world'.find('ello', 0, 1 + len('ello'))
1
>>> 'hello world'.find('ello', 0, 0 + len('ello')) # it starts at index 1, so it's not found
-1