PEP234 iter,意外的屏幕输出

时间:2017-08-23 10:58:48

标签: python iterator

我的代码

import sys

f=open('iter.txt')
for chunk in iter(lambda: f.read(20), ''):  
   n = sys.stdout.write(chunk)
   print(n)

屏幕

Iteration is one of 20
Python’s strongest f20
eatures. At a high l20
evel, you might simp20
ly view
iteration as20
 a way to process it20
ems in a sequence. H20
owever, there is so 20
much more that
is po20
ssible, such as crea20
ting your own iterat20
or objects,
12

我预计会打印出没有这个数值的块。它出现了怎么样? 我发现了这个

iter(callable, sentinel)
This form creates an iterator out of any callable, and will stop when an exception is raised or the sentinel value is returned by the callable.

什么是哨兵价值?

1 个答案:

答案 0 :(得分:1)

sys.stdout.writeprint的效果相同,但最后不添加换行符。因此,如果要删除数值,请删除print(n)