牛骨文教育服务平台(让学习变的简单)

我们有两种大相径庭地输出值方法:表达式语句和 print() 函数(第三种访求是使用文件对象的write() 方法,标准文件输出可以参考 sys.stdout,详细内容参见库参考手册)。

通常,你想要对输出做更多的格式控制,而不是简单的打印使用空格分隔的值。有两种方法可以格式化你的输出:第一种方法是由你自己处理整个字符串,通过使用字符串切割和连接操作可以创建任何你想要的输出形式。string 类型包含一些将字符串填充到指定列宽度的有用操作,随后就会讨论这些。第二种方法是使用 str.format() 方法。

标准模块 string 包括了一些操作,将字符串填充入给定列时,这些操作很有用。随后我们会讨论这部分内容。第二种方法是使用 Template 方法。

当然,还有一个问题,如何将值转化为字符串?很幸运,Python 有办法将任意值转为字符串:将它传入 repr() 或 str() 函数。

函数 str() 用于将值转化为适于人阅读的形式,而 repr() 转化为供解释器读取的形式(如果没有等价的语法,则会发生 SyntaxError 异常)某对象没有适于人阅读的解释形式的话,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
"
>>> hellos = repr(hello)
>>> print(hellos)
"hello, world
"
>>> # 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





(注意第一个例子,print 在每列之间加了一个空格,它总是在参数间加入空格。)

以上是一个 str.rjust() 方法的演示,它把字符串输出到一列,并通过向左侧填充空格来使其右对齐。类似的方法还有 str.ljust() 和 str.center()。这些函数只是输出新的字符串,并不改变什么。如果输出的字符串太长,它们也不会截断它,而是原样输出,这会使你的输出格式变得混乱,不过总强过另一种选择(截断字符串),因为那样会产生错误的输出值(如果你确实需要截断它,可以使用切割操作,例如:x.ljust(n)[:n] )。

还有另一个方法, str.zfill() 它用于向数值的字符串表达左侧填充 0。该函数可以正确理解正负号:

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


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

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

大括号和其中的字符会被替换成传入 str.format() 的参数。大括号中的数值指明使用传入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() )可以在格式化之前转换值:

>>> import math
>>> print("The value of PI is approximately {}.".format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print("The value of PI is approximately {!r}.".format(math.pi))
The value of PI is approximately 3.141592653589793.

字段名后允许可选的 ":" 和格式指令。这允许对值的格式化加以更深入的控制。下例将 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


这种方式与新的内置函数 vars() 组合使用非常有效。该函数返回包含所有局部变量的字典。

要进一步了解字符串格式化方法 str.format(),参见 formatstrings

7.1.1. 旧式的字符串格式化

操作符 % 也可以用于字符串格式化。它以类似 sprintf()-style 的方式解析左参数,将右参数应用于此,得到格式化操作生成的字符串,例如:

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


因为 str.format() 还很新,大量 Python 代码还在使用 % 操作符。然而,因为旧式的格式化方法最终将从语言中去掉,应该尽量使用 str.format()。

进一步的信息可以参见 string-formatting 一节。