Strings in Python have a find("somestring") method that returns the index number for "somestring" in your string.
But let's say I have a string like the following:
"$5 $7 $9 Total Cost: $35 $14"
And I want to find the index of the first occurrence of '$' that occurs after the string "Total Cost" -- I'd like to be able to tell python, search for '$', starting at the index number for "Total Cost", and return the index number (relative to the entire string) for the first occurrence of '$' that you find. The find() method would return 0, and rfind() wouldn't work either in this case.
One kind of kludgy way to do this is the following:
def findStrAfterStr(myString, searchText, afterText):
splitString = myString.split(afterText)
myIndex = len(splitString[0]) + len(afterText) + splitString[1].find(searchText)
return myIndex
myString = "$5 $7 $9 Total Cost: $35 $14"
searchText = "$"
afterText = "Total Cost"
findStrAfterStr(myString, searchText, afterText)
But it seems like there should be an easier way to do this, and I assume there probably is and I just don't know what it is. Thoughts?
This would be particular useful for slicing, when I find myself doing this a lot:
myString[myString.find("startingSubstr"):myString.find("endingSubstr")]
and naturally I want the "endingSubstr" to be the one that occurs after the "startingSubstr".