打印变量时sys.stdout.write和print之间的区别

Rak*_*oth 3 python python-3.x

我想学习sys.stdout.writeprint方法(或函数之间的区别?我应该将它们称为函数或方法吗?)

例如,下面的代码将打印11

a = str(1)
sys.stdout.write (a)
Run Code Online (Sandbox Code Playgroud)

但这将打印1

a = str(1)
print (a)
Run Code Online (Sandbox Code Playgroud)

为什么会有这样的差异?有没有办法让sys.stdout.write()打印1,而不是11?

谢谢!

Jam*_*lls 8

返回值sys.stdout.write()返回no.写的字节数.在这种情况下1,也会在交互式解释提示中打印输入的任何表达式.

例:

>>> import sys
>>> sys.stdout.write("foo")
foo3
Run Code Online (Sandbox Code Playgroud)

如果你想隐藏它,你可以这样做:

>>> nbytes = sys.stdout.write("foo\n")
foo
Run Code Online (Sandbox Code Playgroud)