Jason Hudson
Jason Hudson

Reputation: 97

Return all whole words in a string upto a given index

lets say I have this string which is 42 characters

**
0         1         2       *2*  3         4
0123456789012345678901234567*8*90123456789012
The quick brown fox jumps ov*e*r the lazy dog
**

I want to use it as a search query where the search query can not be longer than 28 characters this i would do by

searchQuery = myString[:28] returning >> The quick brown fox jumps ove

however, I would like it to return The quick brown fox jumps as those are the whole words in the returned string

Upvotes: 0

Views: 33

Answers (1)

cs95
cs95

Reputation: 402473

Look for the last index of a whitespace via str.rindex, then slice on that:

def whole_words_upto(string, index): 
    return string[:string[:index].rindex(' ')]


whole_words_upto('The quick brown fox jumps over the lazy dog', 28)
# 'The quick brown fox jumps'

Note: Does not handle erroneous input or corner cases (that's your task ;-).


A second option is to split and iterate, checking the cumulative length of words before returning:

def whole_words_upto(string, index): 
    total_len = 0
    words = string.split()
    for i, s in enumerate(words):
        if i > 0 and total_len + len(s) >= index:
            return ' '.join(words[:i-1])
        total_len += len(s)

    return string

Upvotes: 1

Related Questions