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
#1
I'm breaking apart a text string line by line with a for loop. Is it possible to get to the next line, without starting at the beginning of the loop?


import requests

webpage=((requests.get('http://SomeRandomWebPage.com')).text)

Counter = 0
for line in webpage.split('\n'):
    Counter = Counter + 1
    print("Doing Stuff Here")
    if Counter == 8:
        ##I want to read the next line from webpage here, without starting at the beginning of the for loop
        print("Do Different Stuff Here")
        continue
Reply
#2
You can use next() to get the next item from an iterator. Here I use next() to skip odd values.
x = iter(range(10))
while True:
    if (num := next(x, None)) is None:
        break
    print(num, end=" ")
    if num % 2 == 0:
        next(x)
Output:
0 2 4 6 8
I don't know that I've ever seen next() using the same iterator as a for loop, but it doesn't appear to do any harm. Here next() gets the last value from x, but the for loop catches the StopIteration exception like normal.
x = iter(range(10))
for num in x:
    print(num, end=" ")
    if num == 8:
        next(x)
Output:
0 1 2 3 4 5 6 7 8
IdMineThat likes this post
Reply
#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
#4
(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.
Reply
#5
You can provide a default value for next() to return when the a StopIteration exception occurs. For bowlofred's example you would use: next_word = next(words, "")
bowlofred likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  File loop curiously skipping files - FIXED mbk34 10 785 Feb-10-2024, 07:08 AM
Last Post: buran
  How do I properly implement restarting a multithreaded python application? MrFentazis 1 623 Jul-17-2023, 09:10 PM
Last Post: JamesSmith
  while loop not working-I am using sublime text editor mma_python 4 1,124 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,655 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
  Graphic line plot with matplotlib, text file in pytho khadija 2 1,375 Aug-15-2022, 12:00 PM
Last Post: khadija
  Find and delete above a certain line in text file cubangt 12 3,449 Mar-18-2022, 07:49 PM
Last Post: snippsat
  CSV to Text File and write a line in newline atomxkai 4 2,675 Feb-15-2022, 08:06 PM
Last Post: atomxkai
  How to prevent python from going to new line in for loop? idknuttin 3 4,913 Feb-11-2022, 05:40 AM
Last Post: deanhystad
  How to make for loop display on 1 Line Extra 3 1,425 Jan-12-2022, 09:29 PM
Last Post: Extra
  python seems to be skipping lines of code alansandbucket 1 4,144 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