查找索引前第一个出现的子字符串

2024-09-28 21:25:14 发布

您现在位置:Python中文网/ 问答频道 /正文

是否有一个与myStr.find(subStr, startInd)的类比,以得到{}mystartInd之前第一次出现的索引。比如从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

编辑二

下面的代码解决了我的问题,但并不十分方便。想问一下是否有一个简单的方法来完成这个任务

^{pr2}$

Tags: 方法代码编辑步骤findam例子print
1条回答
网友
1楼 · 发布于 2024-09-28 21:25:14

^{}采用可选的end参数:

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

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation.

因此,如果您希望subStrendIndex之前subStr结束,可以使用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'

如果您希望subStrendIndex之前的任何地方开始,则必须使用myStr.find(subStr, 0, endIndex + len(subStr))

^{pr2}$

相关问题 更多 >