Python文档学习笔记(10.1)--输入和输出

格式化输出

到目前为止我们遇到过两种输出值的方法:表达式语句print()函数。(第三个方式是使用文件对象的write()方法;标准输出文件可以引用 sys.stdout详细内容参见库参考手册。)

通常你会希望更好地控制输出的格式而不是简单地打印用空格分隔的值。有两种方式格式化你的输出:

1.自己做所有字符串处理;使用字符串切片和串联操作,你可以创建任何你可以想象的布局。

2.使用 str.format() 方法。

 

执行字符串格式化操作。调用此方法的字符串可以包含由大括号{}分隔的文本文本或替换字段。每个替换字段包含位置参数的数字索引或关键字参数的名称。返回字符串的副本,其中每个替换字段将替换为相应参数的字符串值。

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

花括号中的数字可以用来引用传递给str.format()方法的对象的位置。

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

如果str.format()方法中用到关键字参数,那么它们的值通过参数的名称引用。

 

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

 

位置参数和关键字参数可以随意组合:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.

'!a'(运用ascii())、'!s'(运用str())和'!r'(运用repr())可以用来在格式化之前转换相应的值:

>>> contents = 'eels'
>>> print('My hovercraft is full of {}.'.format(contents))
My hovercraft is full of eels.
>>> print('My hovercraft is full of {!r}.'.format(contents))
My hovercraft is full of 'eels'.

字段名后允许可选的':'和格式指令。这允许更好地控制值是何种格式。下面的例子将 Pi 转为三位精度。

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

':'后面紧跟一个整数可以限定该字段的最小宽度。这在美化表格时很有用。

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

如果你有一个不想分裂的非常长的格式字符串,如果你通过名称而不是位置来格式化这个变量会更好一点。有个简单的方法,可以传入一个字典,然后使用'[]'访问。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

这也可以用 ‘**’ 标志将这个字典以关键字参数的方式传入。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

关于str.format()完整的描述,请参见格式字符串语法

 

 

如何将值转换为字符串?

python已经有方法把任何值转换成字符串:使用repr()str() 方法。

str()函数的用意在于返回人类可读的表现形式,而repr()的用意在于生成解释器可读的表现形式

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
>>> print(s)
The value of x is 32.5, and y is 40000...
>>> # The repr() of a string adds string quotes and backslashes:
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # The argument to repr() may be any Python object:
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

这里有两种方法来写一个平方值和立方值的表:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # Note use of 'end' on previous line
...     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

上面的例子演示了字符串对象的str.rjust()方法,它通过在左侧填充空格使字符串在给定宽度的列右对齐。类似的方法还有str.ljust()str.center()这些方法不会输出任何内容,它们只返回新的字符串。如果输入的字符串太长,字符串不会被截断,会完整输出。这将会使列不对齐,但是通常这比截断好,截断会导致不知道原值(如果你真的想要截断,可以加上一个切片操作,例如x.ljust(n)[:n]。)

另外一种方法str.zfill(),它向数值字符串左侧填充零。该函数可以正确识别正负号:

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

 

旧式的字符串格式化

% 也可以用来字符串格式化。它将左边类似sprintf()-风格的参数应用到右边的参数,然后返回这种格式化操作生成的字符串。例如:

>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

printf-风格字符串格式化 一节中,可以找到更多的信息。

posted @ 2019-05-28 23:31  IMWU  阅读(523)  评论(0编辑  收藏  举报