Python Forum

Full Version: what does "yield '\n'" do?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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.
(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!