Python Forum
what does "yield '\n'" do? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: what does "yield '\n'" do? (/thread-7929.html)



what does "yield '\n'" do? - 2sky - Jan-30-2018

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!


RE: what does "yield '\n'" do? - Gribouillis - Jan-30-2018

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.


RE: what does "yield '\n'" do? - 2sky - Jan-30-2018

(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!