Python中sys.stdout.write()和print()的区别

sys.stdout.write()和print()的区别

1、以上两者都是Python的输出方式,有什么区别,我们先看一下官方给出的用法。

  • help('sys.stdout.write')获取其官方用法:
sys.stdout.write(string)
  Write string to stream.
  Returns the number of characters written (which is always equal to the length of the string).
  • help('print')获取其官方用法:
print(value1, value2, ..., 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.
  
## 参数说明:
# sep: 打印的多个值之间以什么字符间隔,默认是空格
# end:打印完值之后以什么字符结尾,默认是换行符
# flush:是否强制刷新输出流,一般用于动态输

2、两者的区别

  • sys.stdout.write()只能输出一个字符串str,而print()可以输出多个值,数据类型多样。
  • print(obj)实际上是调用sys.stdout.write(obj+'\n'),因此print在打印时会自动加个换行符。

拓展:print()字符串格式化输出的三种方式

输入:

taskId = 2
percentage = 98
#保留两位小数
print("任务%d 进度百分比:%.2f %%" % (taskId, percentage))
print("任务{} 进度百分比:{:.2f} %".format(taskId, percentage))
print(f"任务{taskId} 进度百分比:{percentage :.2f} %"

输出:

任务2 进度百分比:98.00 %
任务2 进度百分比:98.00 %
任务2 进度百分比:98.00 
  1. 需要注意的是第二个语句是str.format格式化方法,print("任务{} 进度百分比:{} %".format(taskId, percentage))中的大括号
  • 如果没有标注顺序的0、1、2…,则format()内的参数顺序与字符串中大括号的顺序需要是一致的。
  • 如果标注了顺序,format()内的参数顺序可以不一致。
    例如:
print("任务{1} 进度百分比:{0} %".format(taskId, percentage))
print("任务{1} 进度百分比:{0} %".format(percentage, taskId))

输出:

任务98 进度百分比:2 %
任务2 进度百分比:98 %
  1. 第三个语句f-string格式化方法,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法。f-string在功能方面不逊于传统的 %-formatting 语句和 str.format() 函数,同时性能又优于二者,且使用起来也更加简洁明了,因此对于python3.6以后的版本,更推荐使用f-string
    print(f"任务{taskId} 进度百分比:{percentage :.2f} %"若要控制小数点位数,可以在 {} 内先填入参数再写保留小数点的位数。
  • 12
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值