我们相信:世界是美好的,你是我也是。平行空间的世界里面,不同版本的生活也在继续...

python代码中,存在着sys.stdout.writeprint两个输出函数。那么,这两个函数有什么样的区别呢?在本文中,将对这两个函数进行简要对比,看看使用方式上有什么差别?

苏南大叔:python代码,sys.stdout.write与print有何区别? - python函数输出
python代码,sys.stdout.write与print有何区别?(图2-1)

大家好,这里是苏南大叔的平行空间笔记本博客,这里记录苏南大叔和计算机代码的故事。本文描述在python中,如何使用sys.stdout.writeprint这两个函数。测试环境:win10python@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="")

苏南大叔:python代码,sys.stdout.write与print有何区别? - args-stdout
python代码,sys.stdout.write与print有何区别?(图2-2)

基本结论就是:

  • sys.stdout.write就输出一个字符串,不接收第二个参数。
  • print可输出格式化的字符串,还可同时输出多个字符串,最后还会额外输出结束符。
  • print的结束符默认是个一个回车换行,可替换为空。
  • print替换结束符号后,如果只输出一个字符串的话,就和sys.stdout.write没有区别了。
  • print还有很多高级用法,sys.stdout.write就较为简单了。

相关链接

综述

本文中描述了两个输出函数,并进行了简单对比。个人觉得,这个sys.stdout.write似乎没有啥特别的用。一个print函数应该是走遍天下都不怕吧。

如果本文对您有帮助,或者节约了您的时间,欢迎打赏瓶饮料,建立下友谊关系。
本博客不欢迎:各种镜像采集行为。请尊重原创文章内容,转载请保留作者链接。

 【福利】 腾讯云最新爆款活动!1核2G云服务器首年50元!

 【源码】本文代码片段及相关软件,请点此获取更多信息

 【绝密】秘籍文章入口,仅传授于有缘之人   python