Bottom Page

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!
Quote
#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.
Quote
#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!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Problem about yield, please help!! cls0724 5 248 Apr-08-2020, 05:37 PM
Last Post: deanhystad
  does yield support variable args? Skaperen 0 154 Mar-03-2020, 02:44 AM
Last Post: Skaperen
  generator function that yield from a list buran 9 832 Jun-04-2019, 10:26 PM
Last Post: snippsat
  yield help chakox 5 801 Apr-13-2019, 09:42 PM
Last Post: chakox
  Multiple calls to Python interpreter embedded in C++ application yield segmentation f mmoelle1 0 594 Mar-21-2019, 08:54 PM
Last Post: mmoelle1
  1 == 1 seems to yield false zatlas1 3 597 Jan-07-2019, 01:49 PM
Last Post: Gribouillis
  Yield Keyword 6pathsMadara 6 1,009 Aug-24-2018, 11:43 AM
Last Post: 6pathsMadara

Forum Jump:


Users browsing this thread: 1 Guest(s)