Is there an analogy to myStr.find(subStr, startInd)
in order to get the index of the first occurrence of subStr
before my startInd
. Like taking step -1 instead of 1 from startInd
?
Edit
Here an example:
myStr = "(I am a (cool) str)"
startInd = 9 # print(myStr[startInd]) -> "c"
print(myStr.find(")", startInd)) # -> 13
print(myStr.findBefore("(", startInd)) # -> 8
Edit II
The following code solves my problem but it is not really convenient. Wanted to ask if there is a simple method to fullfill that task
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
str.find
takes an optional end
parameter:
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.
So, if you want subStr
to end before endIndex
, you can use 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'
If you want subStr
to start anywhere before endIndex
, you have to use myStr.find(subStr, 0, endIndex + len(subStr))
instead:
>>> '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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.