Jacek
Jacek

Reputation: 211

Find a word in string with known character position

My problem seems common but i cant find a solution for my case. I want to find a word in a string, using a known index of one of the letters creating said word. For example

'Pizza with extra toppings'.reverse_find(8)
#returns 'with'

I cant find a neat solution. Only thing that comes to my mind is to search for whitespace to the left and right of the String.

Upvotes: 0

Views: 338

Answers (2)

yoav
yoav

Reputation: 322

def find_word_by_index(word, index):
        while (word[index - 1] != " " and index > 0):
            index -= 1

        word = word[index:]

        if word.find(" ") == -1:
            return word

        word = word[:word.find(" ")]
        return word

Upvotes: 1

tobias_k
tobias_k

Reputation: 82939

You could probably use index and rindex with appropriate start and end parameters to search for the next and previous space, but this will be problematic with e.g. punctuation.

Instead, I'd suggest using re.finditer to find and iterate words in the string and compare the bounds of the match to your index.

>>> import re
>>> text = 'Pizza with extra toppings'
>>> i = 8
>>> next(m.group() for m in re.finditer(r"\w+", text) if m.start() <= i < m.end())
'with'

Upvotes: 0

Related Questions