Use .rfind():
>>> s = 'hello'
>>> s.rfind('l')
3
Also don't use str as variable name or you'll shadow the built-in str().
Use .rfind():
>>> s = 'hello'
>>> s.rfind('l')
3
Also don't use str as variable name or you'll shadow the built-in str().
You can use rfind() or rindex()
Python2 links: rfind() rindex()
>>> s = 'Hello StackOverflow Hi everybody'
>>> print( s.rfind('H') )
20
>>> print( s.rindex('H') )
20
>>> print( s.rfind('other') )
-1
>>> print( s.rindex('other') )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
The difference is when the substring is not found, rfind() returns -1 while rindex() raises an exception ValueError (Python2 link: ValueError).
If you do not want to check the rfind() return code -1, you may prefer rindex() that will provide an understandable error message. Else you may search for minutes where the unexpected value -1 is coming from within your code...
Example: Search of last newline character
>>> txt = '''first line
... second line
... third line'''
>>> txt.rfind('\n')
22
>>> txt.rindex('\n')
22
Videos
It depends whether you really want to know the end index or not. Presumably you're actually more interested in the bits of the text after that? Are you then doing something like this?
>>> text[wordEndIndex:]
'n photographs'
If you really do need the index, then do what you've done, but wrap it inside a function that you can call for different texts and words so you don't have to repeat this code. Then it's simple and understandable, if you give the function a descriptive name.
On the other hand, if you're more interested in the bits of text, then don't even bother working out what the index is:
>>> text.split(word)
['fed up of seeing perfect ', ' photographs']
Of course this will get more complicated if the word can appear more than once in the text. In that case maybe you could define a different function to split on the first occurrence of the word and just give back the before and after components, without ever returning any numerical indexes.
I cannot comment on whether this is a better way, but an alternative to what you have suggested would be to find the next space after that word and use that to get the index.
text = "fed up of seeing perfect fashion photographs"
word = "fashion"
temp = text.index(word)
wordEndIndex = temp + text[temp:].index(' ') - 1
Your approach seems more natural, and is possibly faster too.