7. 输入和输出

有几种办法呈现程序输出;数据可以按人类可读形式打印,或写入文件以供未来使用。本章节将讨论一些可能性。

7.1. 更漂亮的输出格式化

So far we’ve encountered two ways of writing values: expression statements print() function. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout . See the Library Reference for more information on this.)

Often you’ll want more control over the formatting of your output than simply printing space-separated values. There are several ways to format output.

  • 要使用 格式化字符串文字 ,开始字符串按 f or F before the opening quotation mark or triple quotation mark. Inside this string, you can write a Python expression between { and } characters that can refer to variables or literal values.

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