Python学习从0开始——007输入与输出
- 一、简单输出
- 二、复杂输出
- 2.1引用变量
- 2.2format()函数
- 2.3手动格式化
- 三、读写文件
- 3.1open()
- 3.2操作文件对象
- 3.3使用 json 保存结构化数据
一、简单输出
str() 函数返回供人阅读的值,repr() 则生成适于解释器读取的值(如果没有等效的语法,则强制执行 SyntaxError)。
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'">>> 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...>>> hello = 'hello, world\n'
>>> repr(hello)
'hello, world\n'>>> repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"
二、复杂输出
2.1引用变量
在字符串开头的引号/三引号前添加 f 或 F,在 { } 字符之间输入变量名称或表达式。
#小数点
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.2f}.')
The value of pi is approximately 3.14.
>>> f'The value of pi is approximately {math.pi:.2f}.'
'The value of pi is approximately 3.14.'#列对齐,在 ':' 后传递整数,为该字段设置最小字符宽度
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678#输出前格式化
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
#repr()
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.
#str()
>>> print(f'My hovercraft is full of {animals!s}.')
My hovercraft is full of eels.
#ascii()
>>> print(f'My hovercraft is full of {animals!a}.')
My hovercraft is full of 'eels'.#=说明符可被用于将一个表达式扩展为表达式文本、等号再加表达式求值结果的形式。
>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'
2.2format()函数
#按位置访问参数
>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam#按名称访问参数
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'#访问参数的属性
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __str__(self):
... return 'Point({self.x}, {self.y})'.format(self=self)
...
>>> str(Point(4, 2))
'Point(4, 2)'#访问参数的项
>>> coord = (3, 5)
>>> 'X: {0[0]}; Y: {0[1]}'.format(coord)
'X: 3; Y: 5'#使用逗号作为千位分隔符
>>> '{:,}'.format(1234567890)
'1,234,567,890'#特定类型的专属格式化
>> import datetime
>>> d = datetime.datetime(2024, 4, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2024-04-04 12:15:58'
2.3手动格式化
#str.rjust()左侧填充空格,对给定宽度字段中的字符串进行右对齐
#str.ljust() 和 str.center():左对齐和居中
>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end='|')
... 1 1| 2 4| 3 9| 4 16| 5 25| 6 36| 7 49| 8 64| 9 81|10 100|#左填充0,能识别正负>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
三、读写文件
3.1open()
#第一个实参是文件名。第二个实参是mode。
>>> f = open('workfile', 'w', encoding="utf-8")
mode 的值包括 ‘r’ ,表示文件只能读取;‘w’ 表示只能写入(现有同名文件会被覆盖);‘a’ 表示打开文件并追加内容,任何写入的数据会自动添加到文件末尾。mode 实参是可选的,省略时的默认值为 ‘r’。
'w’模式调用该函数后,文件无则新建,有则覆盖
在处理文件对象时,最好使用 with 关键字。优点是子句体结束后,文件会正确关闭,即便触发异常也可以。而且,使用 with 相比等效的 try-finally 代码块要简短得多:
>>> with open('workfile', encoding="utf-8") as f:
... read_data = f.read()
...
>>> f.closed
True
但是,调用 f.write() 时,未使用 with 关键字,或未调用 f.close(),即使程序正常退出,也可能导致 f.write() 的参数没有完全写入磁盘。
3.2操作文件对象
#在workfile中输入
This is the first line of the file.
Second line of the file
>>> f = open('workfile', 'r', encoding="utf-8")
#一次读取
>>> f.read()
'This is the first line of the file.\nSecond line of the file'
#读完为空
>>> f.read()
''#循环输出
>>> f = open('workfile', 'r', encoding="utf-8")
>>> for line in f:
... print(line, end='')
...
This is the first line of the file.
Second line of the file#按行读取
>>> f = open('workfile', 'r', encoding="utf-8")
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file'
>>> f.readline()
''#覆盖写文件
>>> f = open('workfile', 'w', encoding="utf-8")
>>> f.write('This is a test\n')
15
>>> f.close()#追加
>>> f = open('workfile', 'a', encoding="utf-8")
>>> value = ('the answer', 42)
>>> s = str(value) # convert the tuple to string
>>> f.write(s)
18
>>> f.close()
3.3使用 json 保存结构化数据
>>> import json
>>> x = [1, 'simple', 'list']
>>> json.dumps(x)
'[1, "simple", "list"]'