详细学习Python的格式化输出

1、输出格式美化

Python两种输出值的方式: 表达式语句和 print() 函数。

第三种方式是使用文件对象的 write() 方法,标准输出文件可以用 sys.stdout 引用。

如果为了输出的形式更加多样,可以使用 str.format() 函数来格式化输出值。

如果要把输出的值转成字符串,可以使用 repr() 或 str() 函数来实现。

  • str(): 函数返回一个用户易读的表达形式。
  • repr(): 产生一个解释器易读的表达形式。
>>> s = 'Hello, php'
>>> str(s)
'Hello, php'
>>> repr(s)
"'Hello, php'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x 的值为: ' + repr(x) + ',  y 的值为:' + repr(y) + '...'
>>> print(s)
x 的值为: 32.5,  y 的值为:40000...
>>> #  repr() 函数可以转义字符串中的特殊字符
... hello = 'hello, php\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, php\n'
>>> # repr() 的参数可以是 Python 的任何对象
... repr((x, y, ('Google', 'php')))
"(32.5, 40000, ('Google', 'php'))"

这里有两种方式输出一个平方与立方的表:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # 注意前一行 'end' 的使用
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

注意: 在第一个例子中, 每列间的空格由 print() 添加。
这个例子展示了字符串对象的 rjust() 方法, 它可以将字符串靠右, 并在左边填充空格。
还有类似的方法, 如 ljust() 和 center()。 这些方法并不会写任何东西, 它们仅仅返回新的字符串。
另一个方法 zfill(), 它会在数字的左边填充 0,如下所示:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

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

>>> print('{}网址: "{}!"'.format('php中文网', 'www.php.cn'))
php中文网网址: "www.php.cn!"

括号及其里面的字符 (称作格式化字段) 将会被 format() 中的参数替换。


在括号中的数字用于指向传入对象在 format() 中的位置,如下所示:

>>> print('{0} 和 {1}'.format('Google', 'php'))
Google 和 php
>>> print('{1} 和 {0}'.format('Google', 'php'))
php 和 Google

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

>>> print('{name}网址: {site}'.format(name='php中文网', site='www.php.cn'))
php中文网网址: www.php.cn

位置及关键字参数可以任意的结合:

>>> print('站点列表 {0}, {1}, 和 {other}。'.format('Google', 'php',
                                                       other='Taobao'))
站点列表 Google, php, 和 Taobao。

‘!a’ (使用 ascii()), ‘!s’ (使用 str()) 和 ‘!r’ (使用 repr()) 可以用于在格式化某个值之前对其进行转化:

>>> import math
>>> print('常量 PI 的值近似为: {}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793>>> print('常量 PI 的值近似为: {!r}。'.format(math.pi))
常量 PI 的值近似为: 3.141592653589793

可选项 ‘:’ 和格式标识符可以跟着字段名。 这就允许对值进行更好的格式化。 下面的例子将 Pi 保留到小数点后三位:

>>> import math
>>> print('常量 PI 的值近似为 {0:.3f}。'.format(math.pi))
常量 PI 的值近似为 3.142

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

>>> table = {'Google': 1, 'php': 2, 'Taobao': 3}
>>> for name, number in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, number))
...
php     ==>          2
Taobao     ==>          3
Google     ==>          1

一个很长的格式化字符串, 而不想将它们分开, 那么在格式化时通过变量名不是位置会是更好。

最简单的就是传入一个字典, 然后使用方括号 ‘[]’ 来访问键值 :

>>> table = {'Google': 1, 'php': 2, 'Taobao': 3}
>>> print('php: {0[php]:d}; Google: {0[Google]:d}; '
          'Taobao: {0[Taobao]:d}'.format(table))
php: 2; Google: 1; Taobao: 3

也可以通过在 table 变量前使用 ‘**’ 来实现相同的功能:

>>> table = {'Google': 1, 'php': 2, 'Taobao': 3}
>>> print('php: {php:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
php: 2; Google: 1; Taobao: 3

2、旧式字符串格式化

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

>>> import math
>>> print('常量 PI 的值近似为:%5.3f。' % math.pi)
常量 PI 的值近似为:3.142

大多数的 Python 代码仍然使用 % 操作符,但是还是多多使用 str.format()才可以实现更多样化的格式化输出。

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值