python内置函数 print()

摘自https://www.cnblogs.com/Dake-T/p/7376779.html

英文文档:

print(*objects, sep=’ ‘, end=’ ’, file=sys.stdout, flush=False)

Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used withbinary mode file objects. For these, use file.write(...) instead.

Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

Changed in version 3.3: Added the flush keyword argument.

函数信息表格

函数原型

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

 

 

参数解释

value 需要打印的内容
... 可以输入多个内容

sep

分隔符,默认为空格;

end

输出结束时补充该参数所指定的字符串,默认为换行符;

file

定义流输出的文件,默认为标准的系统输出sys.stdout,可以重定义为别的文件;

flush

是否立即把内容输出到流文件,不作缓存,默认为False。

返回值

<class 'NoneType'> 返回相应的输出结果。

函数说明

打印相应的内容。

print函数的格式化输出

格式化输出:

1) %字符:标记转换说明符的开始

2) 转换标志:-表示左对齐;+表示在转换值之前要加上正负号;“”(空白字符)表示正数之前保留空格;0表示转换值若位数不够则用0填充

3) 最小字段宽度:转换后的字符串至少应该具有该值指定的宽度。如果是*,则宽度会从值元组中读出。

4) 点‘.’后跟精度值:如果转换的是实数,精度值就表示出现在小数点后的位数。如果转换的是字符串,那么该数字就表示最大字段宽度。如果是*,那么精度将从元组中读出

5) 字符串格式化转换类型

含义

d,i

带符号的十进制整数

o

不带符号的八进制

u

不带符号的十进制

x

不带符号的十六进制(小写)

X

不带符号的十六进制(大写)

e

科学计数法表示的浮点数(小写)

E

科学计数法表示的浮点数(大写)

f,F

十进制浮点数

g

如果指数大于-4或者小于精度值则和e相同,其他情况和f相同

G

如果指数大于-4或者小于精度值则和E相同,其他情况和F相同

C

单字符(接受整数或者单字符字符串)

r

字符串(使用repr转换任意python对象)

s

字符串(使用str转换任意python对象)

 范例1:基本的打印输出(Python 3.6.2 shell 环境)

 
1 >>> print(1,'2',[3.40,'5'],(6,[7,8],'9'))            #参数缺省
2 1 2 [3.4, '5'] (6, [7, 8], '9')
3 >>> print(1, '2', 3.00, sep = '|', end = '
line2')  #使用'|'作为分隔符,'
line2'为结束符
4 1|2|3.0                                             
5 line2 

  范例2:通过更改file参数打印内容到文件(Python 3.6.2 shell 环境)

1 >>> with open(r'D:	emp.txt', 'w') as demo:  
2 print(1, 2, 3, sep = ',', end = '
', file = demo)
5 >>>

  D盘下被新建txt文档’temp.txt’,其内容为:

  1,2,3

  line2

范例3:格式化输出(Python 3.6.2 Shell 环境)

>>> pi=3.14
>>> print('%f'%pi) #默认输出6位小数
3.140000

>>> print('%.3f'%pi)
3.140

print('我叫%s,我今年%d岁'%('小丽',23))

我叫小丽,我今年23岁

>>> print('%-8s%+08d%8s'%('abc',2,'t'))
abc     +0000002       t

09:51:40