【发布时间】:2018-05-31 09:31:38
【问题描述】:
program1.py:
a = "this is a test"
for x in a:
print(x)
program2.py:
a = """this is a test
with more than one line
three, to be exact"""
for x in a:
print(x)
program3.py:
import sys
for x in sys.stdin:
print(x)
infile.txt:
这是一个测试
多行
和第二个例子一样
但话多了
为什么program1和program2都将字符串中的每个字符都输出在单独的一行,但是如果我们运行cat infile.txt | python3 program3.py,它会逐行输出文本?
【问题讨论】:
-
因为
sys.stdin不是字符串——它是一个特殊的类,被构造成逐行读取。 -
sys.stdin不是str对象,它是一个文件对象。
标签: python string python-3.x iteration sys