yesterday the main understanding of the next generator, with the document measurement Lines :
def lines (file): For line in File:yield Lineyield ' \ n ' for I in Lines (Sys.stdin): If I:print iprint '---'
Test document Test_input.txt:
Hellohow is youhow do you dofine
Perform:
Output ResultsTest_output.txt:
Hello------How is---how does------fine------
Note that there is a newline followed by Hello and then the "---". Personally, the reasons are as follows:
First, Test_input.txt is actually a list:
Test_input = [' hello\n ', ' \ n ', ' How to areyou\n ', ' How does you do\n ', ' \ n ', ' fine ']
Second, print prints out something that comes with a newline effect:
print ' 1 ' print ' 2 '
The execution effect is:
That is, 1 is printed first, then wrapped, then printed 2, then wrapped, and the end of execution.
The same is true in Test_output.txt:
print ' hello\n ' first, then wrap, then print '---', print ' \ n ', then wrap, then print '---' ...
Next look at the generator blocks:
def blocks (file): block = [] for line in lines (file): if Line.strip (): block.append (line) elif Block: yield '. Join (block). Strip () block = []test_input = [' hello\n ', ' \ n ', ' How is you\n ', ' How does you do\n ', ' \ n ', ' fine ']for i in Blocks (test_input): If I:print iprint '---'
Execution Result:
strip () function to delete the string in the ' \ n ' such as white space characters (only delete the end-to-end!!! , the middle is not deleted, such as ' \nhello\nhello '. Strip (), the result returned is ' Hello\nhello ', and the result is returned. Append for added after, '. Join means to concatenate the elements in the block with ' ' to return the concatenated string.
Execution process:
The first is line = ' hello\n ', Lines.strip () is true, after if, the value of block is ' hello\n '. After line = ' \ n ', if Line.strip () returns FALSE, the value entered Elif,block is ' hello\n ', return hello and empty block. After line = ' How is you\n ', if is judged as True,block ' How is you\n ', then line = ' How does you do\n ', if the judgment is still true, at this time the block is: [' How is you\n ' How does youdo\n '], then line = ' \ n ', if is judged to be false, enter Elif, '. The value returned after join (block) is ' How is you\nhow do youdo\n ', execute strip () Back to ' How is you\nhow do ' ( note here thatstrip () only removes white space characters from the end of the string and does not delete the middle of the string ):
In conclusion,
Test_input = [' hello\n ', ' \ n ', ' How-areyou\n ', ' How does you do\n ', ' \ n ', ' fine '] after the generator blocks, the resulting result should be:
[' Hello ', how is you\nhow do ', ' fine ']
That is, the input text is returned to the block
Python Basic Tutorial Notes-item 1-Instant tag-day2