Find end of word index in python

Is there a good (er) way to find the ending index of a word in a string?

My method is this:

text = "fed up of seeing perfect fashion photographs" word = "fashion" wordEndIndex = text.index(word) + len(word) - 1 
+7
python string find indexing
source share
2 answers

I can’t comment on whether this is the best way, but an alternative to what you suggested would be to find the next space after this word and use it 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 perhaps faster.

0
source share

It depends on whether you really want to know the final index or not. Presumably you are more interested in the text bits after that? Are you doing something like that?

 >>> text[wordEndIndex:] 'n photographs' 

If you really need an index, then do what you did, but wrap it inside a function that you can call for different text and word so you don't have to repeat this code. Then it is simple and understandable if you give the function a descriptive name.

On the other hand, if you are more interested in text bits, then don't even worry about what an index is:

 >>> text.split(word) ['fed up of seeing perfect ', ' photographs'] 

Of course, this will be complicated if the word can appear more than once in the text. In this case, perhaps you could define another function to divide by the first occurrence of the word and simply return the components before and after without returning any numerical indices.

0
source share

All Articles