更复杂的输出格式

表达式语句 和 ​print()​ 函数。第三种方法是使用文件对象的 ​write()​ 方法;标准输出文件称为 ​sys.stdout​

对输出格式的控制不只是打印空格分隔的值,还需要更多方式。

使用 ​​格式化字符串字面值​​​ ,要在字符串开头的引号/三引号前添加 ​​f​​ 或 ​​F​​ 。在这种字符串中,可以在 ​​{​​ 和 ​​}​​ 字符之间输入引用的变量,或字面值的 Python 表达式。

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

字符串的 str.format() 方法需要更多手动操作。该方法也用 ​{​ 和 ​}​​​ 标记替换变量的位置,虽然这种方法支持详细的格式化指令,但需要提供格式化信息。

>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
>>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes 49.67%'

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\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'))"