首页 > 编程语言 > 详细

python3之print函数

时间:2021-06-25 16:44:49      阅读:11      评论:0      收藏:0      [点我收藏+]

先通过help命令查看print函数的相关信息。

技术分享图片

第一行表示这是一个内置函数,功能为打印输出

Help on built-in function print in module builtins:

参数说明:

print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)

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.

1、直接打印输出,无参数

技术分享图片

2、sep参数

打印两个值,默认以空格分隔

技术分享图片

如果想以逗号分隔,可使用sep参数,如下:

技术分享图片

3、file参数

默认打印到标准输出中,但是也可以打印到外部文件中,如下例把hello world打印到外部文件1.txt中

1 f = open("1.txt","w")
2 
3 s = "hello world"
4 print(s,file=f)
5 
6 f.close

打印结果如下,1.txt文件中增加了hello world内容。

技术分享图片

 

 打印到stderr

import sys

s = "this is error message"

print("printing to stderr...")
print(s,file=sys.stderr)

4、end参数

print函数默认以换行符结尾,参数为end="\n",也可以指定其他结尾,如下面例子中默认以空字符为结尾

print("这是第一行")
print("这是第二行")

print("这是第一行",end="")
print("这是第二行")

 输出结果如下:

技术分享图片

 5、打印变量

打印变量是用f加上{变量名称}的形式,这个是python3的新特性

技术分享图片

 

 

python3之print函数

原文:https://www.cnblogs.com/snow2021/p/14931176.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!