【问题标题】:Find First Occurrence of Substring Before Index在索引之前查找子字符串的第一次出现
【发布时间】:2018-11-21 01:11:11
【问题描述】:

为了得到subStr之前我的startInd第一次出现的索引,有没有类似于myStr.find(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

【问题讨论】:

  • 您只是在寻找rfind吗?
  • @abarnert 不完全是。我在我的问题中添加了一个示例,以便更清楚地说明我的意思。

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


【解决方案1】:

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

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

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

所以,如果你想让subStrendIndex 之前结束,你可以使用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))

>>> '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

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 2016-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2010-12-25
    • 1970-01-01
    相关资源
    最近更新 更多