在索引之前找到第一个子串的出现

时间:2018-06-11 17:59:29

标签: python string python-3.x find substring

是否有myStr.find(subStr, startInd)的类比,以便在subStr 之前获得startInd 第一次出现的索引。喜欢从startInd中取步骤-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

1 个答案:

答案 0 :(得分:1)

str.find采用可选的end参数:

  

str.find(sub [,start [,end]])

     

返回字符串中的最低索引,其中在切片s [start:end]中找到substring sub。可选参数start和end是   解释为切片表示法。

因此,如果您希望在subStr之前endIndex 结束,则可以使用myStr.find(subStr, 0, endIndex)

>>> 'hello world'.find('ello', 0, 5)
1
>>> 'hello world'.find('ello', 0, 4)  # "ello" ends at index 5, so it's not found
-1
>>> 'hello world'[0:4]
'hell'

如果您希望在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