
5.2 格式化字符串
在编写程序的过程中,经常需要进行格式化的输出,Python中提供了字符串格式化操作符%,非常类似C语言中的printf()函数的字符串的格式化(C语言中也使用%)。格式化字符串时,Python使用一个字符串作为一个模板,模板中有格式符,这些格式符为真实数值预留位置,并说明真实数值应该呈现的格式。
Python中常见的字符串格式化符号可以包含的类型见表5-1。
表5-1 格式符类型

通过“%”可以进行字符串的格式化,但是“%”经常会结合下面的操作辅助指令一起使用,如表5-2所示。
表5-2 操作辅助符

5.2.1 格式化字符串符号的简单使用

下面一起通过对三个格式化字符串符号%s,%d,%f的简单使用,来看看格式化字符串符号的用法。
【例5-9】%s字符串的简单使用。

程序运行结果如图5-9所示。

图5-9 %s使用结果
【例5-10】%d整数的简单使用。

程序运行结果如图5-10所示。
【例5-11】%f浮点数的简单使用。

程序运行结果如图5-11所示。

图5-10 %d使用结果

图5-11 %f使用结果
5.2.2 字符宽度和精度

字符宽度:转换后的值所保留的最小字符个数。
精度:对于数字转换来说,结果中应包含的小数位数;对于字符串转换来说,转换后的值所能包含的最大字符个数。
表示格式:字符宽度、精度,若给出精度,则必须包含点号。
【例5-12】指定宽度。

程序运行结果如图5-12所示。
【例5-13】浮点数精度。

程序运行结果如图5-13所示。

图5-12 指定宽度结果

图5-13 浮点数精度结果
5.2.3 对齐和用0填充

字符串对齐有多种方法,这里介绍两种方法。
第一种:字符^、<、>分别是居中、左对齐、右对齐,后面带宽度。
【例5-14】使用字符^、<、>进行数据的对齐。

程序运行结果如图5-14所示。
第二种:在Python中打印字符串时可以调用ljust(左对齐)、rjust(右对齐)和center(中间对齐)来输出整齐美观的字符串。
如果希望字符串的长度固定,给定的字符串又不够长度,可以通过rjust、ljust和center三个方法来给字符串补全空格。rjust为向右对齐,在左边补空格;ljust为向左对齐,在右边补空格;center为让字符串居中,在左右补空格。
【例5-15】调用ljust()、rjust()、center()函数进行数据的对齐。

程序运行结果如图5-15所示。

图5-14 使用字符^、<、>对齐结果

图5-15 调用函数对齐结果
同样,用0填充也有多种方法,下面介绍两种。
第一种,使用:号后面带填充的字符,只能是一个字符,若无指定则默认是用空格填充。
【例5-16】使用:号进行0填充。

程序运行结果如图5-16所示。
第二种:zfill()方法返回指定长度的字符串,原字符串右对齐,前面填充0。
zfill()方法语法:str.zfill(width)。参数width指定字符串的长度。原字符串右对齐,前面填充0。返回指定长度的字符串。
【例5-17】使用zfill()函数进行0填充。

程序运行结果如图5-17所示。

图5-16 使用:号进行0填充结果

图5-17 使用函数进行0填充结果