Python Forum
Skipping line in text without Restarting Loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Skipping line in text without Restarting Loop
#3
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.
IdMineThat likes this post
Reply


Messages In This Thread
RE: Skipping line in text without Restarting Loop - by bowlofred - Apr-05-2022, 03:24 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  File loop curiously skipping files - FIXED mbk34 10 956 Feb-10-2024, 07:08 AM
Last Post: buran
  How do I properly implement restarting a multithreaded python application? MrFentazis 1 662 Jul-17-2023, 09:10 PM
Last Post: JamesSmith
  while loop not working-I am using sublime text editor mma_python 4 1,193 Feb-05-2023, 06:26 PM
Last Post: deanhystad
  Trying to loop through code to plot seaborn line plots across multiple subplots eyavuz21 0 1,732 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
  Graphic line plot with matplotlib, text file in pytho khadija 2 1,437 Aug-15-2022, 12:00 PM
Last Post: khadija
  Find and delete above a certain line in text file cubangt 12 3,632 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,775 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  How to prevent python from going to new line in for loop? idknuttin 3 5,014 Feb-11-2022, 05:40 AM
Last Post: deanhystad
  How to make for loop display on 1 Line Extra 3 1,489 Jan-12-2022, 09:29 PM
Last Post: Extra
  python seems to be skipping lines of code alansandbucket 1 4,226 Jun-22-2021, 01:18 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020