输入输出
常用的输入输出内置函数:
| 函数 | 说明 | 示例 |
|---|---|---|
print(*objects, sep, end) | 打印,sep 是分隔符(默认空格),end 是结尾符(默认换行) | print(1, 2, sep='-') → 1-2 |
input(prompt) | 读取用户输入,返回值总是字符串 | name = input('姓名:') |
open(file, mode, encoding) | 打开文件返回文件对象 | open('a.txt', 'w', encoding='utf-8') |
format(value, spec) | 按格式规范转换 | format(3.14, '.2f') → '3.14' |
help(obj) | 查看对象的帮助文档 | help(str.upper) |
breakpoint() | 在该行暂停进入 pdb 调试器(Python 3.7+) |
示例
# print:自定义分隔符与结尾符
print(1, 2, 3, sep='-') # 1-2-3
print('不换行', end='') # end 默认为 '\n'
# input:读取输入后常需要类型转换
name = input('请输入姓名:')
age = int(input('请输入年龄:'))
# format:按格式规范化
print(format(3.14159, '.2f')) # 3.14
print(format(15, '08b')) # 00001111,8 位二进制
# help:查看帮助
help(str.upper)
# breakpoint:程序运行到该行时进入 pdb 调试
# breakpoint()
open:文件读写
常用 mode:r 读(默认)、w 写(覆盖)、a 追加、b 二进制、+ 读写。
# 推荐用 with,语句块结束自动关闭文件
with open('demo.txt', 'w', encoding='utf-8') as f:
f.write('hello')
with open('demo.txt', encoding='utf-8') as f:
print(f.read()) # hello