Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
what does "yield '\n'" do?
#1
I have seen this sample code from one python book:

def lines(file):
    for line in file: yield line
    yield '\n'
    
def blocks(file):
    block = []
    for line in lines(file):
        if line.strip():
            block.append(line)
        elif block:
            yield ''.join(block).strip()
            block = []
I am not sure what does "yield '\n'" do in line 3. I am also not sure when these two conditions: "if line.strip()" and "elif block" will be triggered. I am pretty new in python. Hope you guys can help me understand this code more. thanks!
Reply
#2
yield '\n' generates a string containing a single newline after all the lines have been generated. It is a way to ensure that there is a newline at the end of the file by adding a newline. The if line.strip() test succeeds if it remains anything in the line after removing all the white space at both ends.
Reply
#3
(Jan-30-2018, 09:10 AM)Gribouillis Wrote: yield '\n' generates a string containing a single newline after all the lines have been generated. It is a way to ensure that there is a newline at the end of the file by adding a newline. The if line.strip() test succeeds if it remains anything in the line after removing all the white space at both ends.

Thanks a lot for your explanation!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  yield usage as statement or expression akbarza 5 752 Oct-23-2023, 11:43 AM
Last Post: Gribouillis
  Using list comprehension with 'yield' in function tester_V 5 1,176 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Yield generator weird output Vidar567 8 3,198 Nov-23-2020, 10:59 PM
Last Post: deanhystad
  Trying to access next element using Generator(yield) in a Class omm 2 1,935 Oct-19-2020, 03:36 PM
Last Post: omm
  Yield statement question DPaul 6 2,449 Sep-26-2020, 05:18 PM
Last Post: DPaul
  Problem about yield, please help!! cls0724 5 2,815 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 1,643 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 4,109 Jun-04-2019, 10:26 PM
Last Post: snippsat
  yield help chakox 5 3,209 Apr-13-2019, 09:42 PM
Last Post: chakox
  Multiple calls to Python interpreter embedded in C++ application yield segmentation f mmoelle1 0 2,797 Mar-21-2019, 08:54 PM
Last Post: mmoelle1

Forum Jump:

User Panel Messages

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