python代码,sys.stdout.write与print有何区别?
发布于 作者:苏南大叔 来源:程序如此灵动~
在python代码中,存在着sys.stdout.write和print两个输出函数。那么,这两个函数有什么样的区别呢?在本文中,将对这两个函数进行简要对比,看看使用方式上有什么差别?

大家好,这里是苏南大叔的程序如此灵动博客,这里记录苏南大叔和计算机代码的故事。本文描述在python中,如何使用sys.stdout.write和print这两个函数。测试环境:win10,python@3.6.8。
输出官方帮助信息
使用help()函数,输出函数帮助信息。
help(sys.stdout.write)Help on built-in function write in sys.stdout:
sys.stdout.write = write(text, /) method of _io.TextIOWrapper instance
Write string to stream.
Returns the number of characters written (which is always equal to
the length of the string).
Help on built-in function print in module builtins:help('print')print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.函数对比
测试代码:
sys.stdout.write("arg1")
print("arg1","arg2")
print("arg1","arg2",end="")
基本结论就是:
sys.stdout.write就输出一个字符串,不接收第二个参数。print可输出格式化的字符串,还可同时输出多个字符串,最后还会额外输出结束符。print的结束符默认是个一个回车换行,可替换为空。print替换结束符号后,如果只输出一个字符串的话,就和sys.stdout.write没有区别了。print还有很多高级用法,sys.stdout.write就较为简单了。
相关链接
综述
本文中描述了两个输出函数,并进行了简单对比。个人觉得,这个sys.stdout.write似乎没有啥特别的用。一个print函数应该是走遍天下都不怕吧。