格式化输出

有四种格式化输出方式。

格式化字符串字面量

格式化字符串字面量(formatted string literals)open in new window,也简称 f-strings,通过在字符串前面加一个 F 或者 f,可以允许我们在字符串使用表达式({expression})。

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

冒号后面是一个格式化表达式,在Format Specification Mini-Languageopen in new window可以查看详细信息。

str.format()

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

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

我们可以给每一个表达式设置一个索引或者名称。

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam
>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
1
2
3
4
5
6
7

手动格式化

通过 str.rjust()str.ljust()str.center()srt.zfill() 等方法来格式化。这几个函数的功能分别是右对齐、左对齐、居中对齐和左补零填充。

>>> 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

老式的字符串格式化

通过 'string' % values 的形式来实现字符串格式化,string 中的所有 % 都会被 values 中的相应元素替换。

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

更多格式化信息可以在 printf-style String Formatting open in new window 查看

读写文件

open() 函数open in new window返回一个文件对象,我们可以对这个文件对象进行一些操作。open() 函数支持指定读写模式,r 为只读模式,w 为只写模式,a 为追加模式,r+ 为读写模式。

通常来说,文件被以文本文件模式打开,我们可以通过参数来改变文件模式,比如 b 参数可以指定以二进制模式打开。

在文本模式中,读取的文本行,换行符都是 \n,Python 内部根据不同平台做了差异化处理。即读取的时候会将不同平台的换行符转换成 \n,写入的时候会将 \n 转换成不同平台的换行符。

操作文件对象

通过 open() 函数拿到文件对象以后,我们可以通过 f.read(size) 方法读取一段文本,未指定 size 则读取全部内容(当心读取大文件问题)。在到文件末尾时,f.read() 会返回空字符串('')。

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
1
2
3
4

f.readline() 会逐行读取文本,每一行末尾都是一个换行符(\n)。读到文件末尾则返回空字符串。

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
1
2
3
4
5
6

我们可以通过 list(f) 或者 f.readlines() 读取文件内所有的行。

f.write(string) 可以写入文件,返回写入的文本长度。

>>> f.write('This is a test\n')
15
1
2

f.tell() 返回当前读取的位置。我们可以通过 f.seek(offset, whence) 来改变读取位置。当 whence 为 0 时,从文件开始计算偏移量;当 whence 为 1 时,从当前读取位置计算偏移量;当 whence 为 2 时,从文件末尾开始计算偏移量。

使用 json 保存结构化数据

我们可以通过 jsonopen in new window 这个模块。

>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'
1
2
3
4

如果已经拿到文件对象,则可以直接通过 dumpload 函数来实现写入和读取文件内容。

json.dump(x, f)
x = json.load(f)
1
2

关注微信公众号,获取最新推送~

加微信,深入交流~