Apr-05-2022, 03:32 AM
(Apr-05-2022, 03:24 AM)bowlofred Wrote: You could make an explicit iterator from the list returned from split(), then you can loop over the iterator, but also pull from it inside the loop.
Here's a loop that prints every word in a list of words, but if the word starts with "t", then it also tacks on the next word in the list.
Note that if the last word in the list started with "t", the next() would generate an error.
mytext = "This is a list of words that can be iterated." words = iter(mytext.split()) # words holds an iterator of the list for word in words: # For loop will read most of the iterator if word.lower().startswith("t"): next_word = next(words) # next() can also consume from the iterator print(f" {word} / {next_word}") else: # If the word doesn't start with "t", print it alone print(word)
Output:This / is a list of words that / can be iterated.
You are a god. I got it working AND learned something.
Thanks to both of you.