
1.4.2 print()函数

1-8 print()函数
1.多变量输出
前面章节中使用print()函数时,都只输出了一个变量,但实际上print()函数完全可以同时输出多个变量,而且它具有更多丰富的功能。
print()函数的详细语法格式如下:

式中,value参数可以接受任意多个变量或值,因此print()函数完全可以输出多个值。
【例1-19】 使用input()来输入数字,并转化为int。

运算结果:

从本例的输出结果来看,使用print()函数输出多个变量时,print()函数默认以空格隔开多个变量。如果希望改变默认的分隔符,可通过sep参数进行设置,如sep='|'等。
2.格式化字符串(格式化输出)
print()函数使用以%开头的转换说明符对各种类型的数据进行格式化输出,如表1-4所示。转换说明符是一个占位符,它会被后面表达式(变量、常量、数字、字符串、加减乘除等各种形式)的值代替。
表1-4 格式化输出转换说明符

【例1-20】 使用格式化输出。

运算结果:

3.指定最小输出宽度
可以使用下面的格式指定最小输出宽度(至少占用多少个字符的位置):

【例1-21】 指定最小输出宽度。

运算结果:

从本例的运行结果可以发现,对于整数和字符串,当数据的实际宽度小于指定宽度时,会在左侧以空格补齐;当数据的实际宽度大于指定宽度时,会按照数据的实际宽度输出,即num宽度为5,指定为%4d时,还是按照数据的实际宽度5进行输出。
4.指定对齐方式
在默认情况下,print()输出的数据总是右对齐的。也就是说,当数据不够宽时,数据总是靠右侧输出,而在左侧补充空格以达到指定的宽度。Python允许在最小宽度之前增加一个标志来改变对齐方式,Python支持的标志如表1-5所示。
表1-5 Python支持的标志

另外需要说明的如下。
1)对于整数,指定左对齐时,在右侧补0是没有效果的,因为这样会改变整数的值。
2)对于小数,以上3个标志可以同时存在。
3)对于字符串,只能使用“-”标志。
【例1-22】 指定对齐方式。

运算结果:

5.指定小数精度
对于小数(浮点数),print()允许指定小数点后的数字位数,即指定小数的输出精度。精度值需要放在最小宽度之后,中间用点号“.”隔开;也可以不写最小宽度,只写精度。具体格式如下:

式中,m表示最小宽度,n表示输出精度,“.”是必须存在的。
【例1-23】 指定小数精度。

运算结果:
