In python, I sometimes write a while statement like
i = 0 while <condition that involves i>: i += 1
The goal is, of course, to check the number of time the condition is true.
I was wondering if there's a more simple, pythonic way to do it ? something like
i = while <condition that involves i>, maybe with the walrus operator ?
Here's a more concrete example:
def get_word_num_with_character_index(string: str, index: int) -> int: """ returns the number of the word containing a character, specified by an index :param string: the string to analyze :param index: the index of the character :return: the number of the word containing the specified character """ split_string = string.split(" ") i = 0 while len(" ".join(split_string[:i])) <= index: i += 1 return i - 1 print(get_word_num_with_character_index("jean de la fontaine", 8)) # prints 2, the index of the word containing the 8th character
How to simplify it ?