Python3的格式化输出

一般来说,我们希望更多的控制输出格式,而不是简单的以空格分割。这里有两种方式:

第一种是由你自己控制。使用字符串切片、连接操作以及 string 包含的一些有用的操作。
第二种是使用str.format()方法。
下面给一个示例:

 1 # 第一种方式:自己控制 
 2 for x in range(1, 11): 
 3   print(str(x).rjust(2), str(x*x).rjust(3), end=' ') 
 4   print(str(x*x*x).rjust(4)) 
 5   
 6 # 第二种方式:str.format() 
 7 for x in range(1, 11): 
 8   print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) 
 9   
10 # 输出都是: 
11 # 1  1  1 
12 # 2  4  8 
13 # 3  9  27 
14 # 4 16  64 
15 # 5 25 125 
16 # 6 36 216 
17 # 7 49 343 
18 # 8 64 512 
19 # 9 81 729 
20 # 10 100 1000 

第一种方式中,字符串对象的 str.rjust() 方法的作用是将字符串靠右,并默认在左边填充空格,类似的方法还有 str.ljust() 和 str.center() 。这些方法并不会写任何东西,它们仅仅返回新的字符串,如果输入很长,它们并不会截断字符串。我们注意到,同样是输出一个平方与立方表,使用str.format()会方便很多。

str.format()的基本用法如下:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) 
We are the knights who say "Ni!"

括号及括号里的字符将会被 format() 中的参数替换.。括号中的数字用于指定传入对象的位置:

>>> print('{0} and {1}'.format('Kobe', 'James')) 
Kobe and James 
>>> print('{1} and {0}'.format('Kobe', 'James')) 
James and Kobe 

如果在 format() 中使用了关键字参数,那么它们的值会指向使用该名字的参数:

>>> print('The {thing} is {adj}.'.format(thing='flower', adj='beautiful')) 
The flower is beautiful. 

可选项':'和格式标识符可以跟着 field name,这样可以进行更好的格式化:

>>> import math 
>>> print('The value of PI is {0:.3f}.'.format(math.pi)) 
The value of PI is 3.142. 

在':'后传入一个整数,可以保证该域至少有这么多的宽度,用于美化表格时很有用:

>>> table = {'Jack':4127, 'Rose':4098, 'Peter':7678} 
>>> for name, phone in table.items(): 
...   print('{0:10} ==> {1:10d}'.format(name, phone)) 
...  
Peter   ==>    7678
Rose    ==>    4098
Jack    ==>    4127

我们还可以将参数解包进行格式化输出。例如,将table解包为关键字参数:

table = {'Jack':4127, 'Rose':4098, 'Peter':7678} 
print('Jack is {Jack}, Rose is {Rose}, Peter is {Peter}.'.format(**table)) 
# 输出:Jack is 4127, Rose is 4098, Peter is 7678. 

补充:

% 操作符也可以实现字符串格式化。它将左边的参数作为类似 sprintf() 式的格式化字符串,而将右边的代入:

1 import math 
2 print('The value of PI is %10.3f.' %math.pi) 
3 # 输出:The value of PI is   3.142.

因为这种旧式的格式化最终会从Python语言中移除,应该更多的使用 str.format() 。

(本文转载自脚本之家http://www.jb51.net/article/53849.htm#comments)

原文地址:https://www.cnblogs.com/xixislz/p/7462311.html