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