一、输出方式
1、 print输出
2、 格式化字符串字面值:
要在字符串开头的引号/三引号前添加 f 或 F
>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'
3、 字符串的 str.format() 方法。该方法也用 { 和 } 标记替换变量的位置。
位置参数:
>>> year = 2022
>>> event = '新冠肺炎'
>>> '{0} Yes votes {1}'.format(year,event)
'2022 Yes votes 新冠肺炎'
>>> 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.
关键字参数结合位置参数:
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
The story of Bill, Manfred, and Georg.
如果不想分拆较长的格式字符串,最好按名称引用变量进行格式化,不要按位置。这项操作可以通过传递字典,并用方括号 ‘[]’ 访问键来完成。
>>> 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**
>>> 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
4、 读写文件
open() 返回一个 file object ,最常使用的是两个位置参数和一个关键字参数:open(filename, mode, encoding=None)
>>> f = open('workfile', 'w', encoding="utf-8")
第一个实参是文件名字符串。第二个实参是包含描述文件使用方式字符的字符串。
mode 的值包括 ‘r’ ,表示文件只能读取;
‘w’ 表示只能写入(现有同名文件会被覆盖);
‘a’ 表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。
‘r+’ 表示打开文件进行读写。
mode 实参是可选的,省略时的默认值为 ‘r’。
在处理文件对象时,最好使用 with 关键字。优点是,子句体结束后,文件会正确关闭,即便触发异常也可以。而且,使用 with 相比等效的 try-finally 代码块要简短得多:
>>> with open('workfile', encoding="utf-8") as f:
... read_data = f.read()
...
# We can check that the file has been automatically closed.
>>> f.closed
>>> True
如果没有使用 with 关键字,则应调用 f.close() 关闭文件,即可释放文件占用的系统资源:
警告 调用 f.write() 时,未使用 with 关键字,或未调用 f.close(),即使程序正常退出,也**可能** 导致 f.write() 的参数没有完全写入磁盘。
二、各种输出格式
1、 如果不需要花哨的输出,只想快速显示变量进行调试,可以用 repr() 或 str() 函数把值转化为字符串。
str() 函数返回供人阅读的值,repr() 则生成适于解释器读取的值
>>> x = 3*8
>>> str(x)
'24'
>>> repr(x)
'24'
>>> y = 'hello world'
>>> str(y)
'hello world'
>>> repr(y)
"'hello world'"
>>>
2、 在 ‘:’ 后传递整数,为该字段设置最小字符宽度,常用于列对齐:
>>> for name, phone in table.items():
... print(f'{name:8} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
>>> for name, phone in table.items():
... print(f'{name:8} ==> {phone:10}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:22}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
3、用str.rjust() str.ljust() str.center() 方法填充空格
字符串对象的 str.rjust() 方法通过在左侧填充空格,对给定宽度字段中的字符串进行右对齐。同类方法还有 str.ljust() 和 str.center() 。这些方法不写入任何内容,只返回一个新字符串,如果输入的字符串太长,它们不会截断字符串,而是原样返回;虽然这种方式会弄乱列布局,但也比另一种方法好,后者在显示值时可能不准确(如果真的想截断字符串,可以使用 x.ljust(n)[:n] 这样的切片操作 。
>>> 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
另一种方法是str.zfill() ,该方法在数字字符串左边填充零,且能识别正负号:
>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
4、指定字符的整数部分位数,小数部分位数
看代码示例:
import math
k = '%5.3f' % math.pi
j = '%6.3f' % math.pi
l = '%6.4f' % math.pi
print(k)
print(j)
print(l)
print('the value of pi is %6.4f' % math.pi)
print('the value of pi is %6.3f' % math.pi)
print('the value of pi is %5.3f' % math.pi)
console.out:
3.142
3.142
3.1416
the value of pi is 3.1416
the value of pi is 3.142
the value of pi is 3.142
5、 文件对象的方法(with open)
本节下文中的例子假定已创建 f 文件对象。
f.read(size) 可用于读取文件内容,它会读取一些数据,并返回字符串(文本模式),或字节串对象(在二进制模式下)。 size 是可选的数值参数。省略 size 或 size 为负数时,读取并返回整个文件的内容;文件大小是内存的两倍时,会出现问题。size 取其他值时,读取并返回最多 size 个字符(文本模式)或 size 个字节(二进制模式)。如已到达文件末尾,f.read() 返回空字符串(‘’)。
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
f.readline() 从文件中读取单行数据;字符串末尾保留换行符(\n),只有在文件不以换行符结尾时,文件的最后一行才会省略换行符。这种方式让返回值清晰明确;只要 f.readline() 返回空字符串,就表示已经到达了文件末尾,空行使用 ‘\n’ 表示,该字符串只包含一个换行符。
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
从文件中读取多行时,可以用循环遍历整个文件对象。这种操作能高效利用内存,快速,且代码简单:
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file
如需以列表形式读取文件中的所有行,可以用 list(f) 或 f.readlines()。
f.write(string) 把 string 的内容写入文件,并返回写入的字符数。
>>> f.write('This is a test\n')
15
写入其他类型的对象前,要先把它们转化为字符串(文本模式)或字节对象(二进制模式):
>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
18
f.tell() 返回整数,给出文件对象在文件中的当前位置,表示为二进制模式下时从文件开始的字节数,以及文本模式下的意义不明的数字。
f.seek(offset, whence) 可以改变文件对象的位置。通过向参考点添加 offset 计算位置;参考点由 whence 参数指定。 whence 值为 0 时,表示从文件开头计算,1 表示使用当前文件位置,2 表示使用文件末尾作为参考点。省略 whence 时,其默认值为 0,即使用文件开头作为参考点。
>>> f = open('workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # Go to the 6th byte in the file
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
13
>>> f.read(1)
b'd'
在文本文件(模式字符串未使用 b 时打开的文件)中,只允许相对于文件开头搜索(使用 seek(0, 2) 搜索到文件末尾是个例外),唯一有效的 offset 值是能从 f.tell() 中返回的,或 0。其他 offset 值都会产生未定义的行为。
文件对象还支持 isatty() 和 truncate() 等方法,但不常用;文件对象的完整指南详见库参考。