7. 基本输入输出

input() 输入函数

Python 提供了内置函数 input(),用于接收用户的键盘输入,一般用法为:x = input("提示文字")无论输入的是数字还是字符串,input() 函数返回的结果都是字符串,数据输入后,再根据需要转换成其它数据类型。

python
name = input("请输入名字:")    # 输入数据
print("你的名字是:", name)     # 输出数据

i = input("请输入数字:")       # 输入的是字符类型
print(type(i))                  # <class 'str'>
# i = int(input("请输入数字:")) # 将字符类型转换为整数

▶ 运行结果:

输出
请输入名字:小明
你的名字是: 小明
请输入数字:
<class 'str'>

print() 格式化输出

Python 使用内置函数 print() 将结果输出,格式为:print(输出的内容)。输出的内容可以是数字和字符串,也可以是变量或表达式。print() 函数默认是换行的,即输出语句后自动切换到下一行,如果要实现输出不换行的功能,可以设置 end=''

python
print("白日依山尽")  # 自动换到下一行
print("黄河入海流")
print("欲穷千里目")
print("更上一层楼")

▶ 运行结果:

输出
白日依山尽
黄河入海流
欲穷千里目
更上一层楼

2. % 格式化(传统方式)

格式符 含义
%o输出八进制整数
%d输出十进制整数
%x输出十六进制整数
%f保留 6 位有效数字(浮点数),%.3f 则保留 3 位
%e指数形式输出(科学记数法)
%s字符串输出
python
a = 30
print('%o' % a)  # 八进制是 36
print('%d' % a)  # 十进制是 30
print('%x' % a)  # 十六进制是 1e

nHex = 0xFF
print("十六进制是%x,十进制是%d,八进制是%o" % (nHex, nHex, nHex))
# 十六进制是ff,十进制是255,八进制是377

# 浮点数
print('%f' % 2.22)     # 默认保留 6 位小数
print('%.1f' % 2.22)   # 取 1 位小数
print('%e' % 2.22)     # 科学计数法
print('%.3e' % 2.22)   # 取 3 位小数,科学计数法
print('%g' % 2222.2222)    # 默认 6 位有效数字
print('%.7g' % 2222.2222)  # 取 7 位有效数字
print('%.2g' % 2222.2222)  # 取 2 位有效数字,自动转科学计数法

# 字符串格式化
print('%s' % 'hello world')      # hello world
print('%20s' % 'hello world')    # 右对齐,占 20 位
print('%-20s' % 'hello world')   # 左对齐,占 20 位
print('%.2s' % 'hello world')    # 截取 2 位 → he
print('%10.2s' % 'hello world')  # 右对齐,10 位占位符,截取 2 位
print('%-10.2s' % 'hello world') # 左对齐,10 位占位符,截取 2 位

name = '小明'
age = 13
print('姓名:%s,年龄:%d' % (name, age))
# 姓名:小明,年龄:13

▶ 运行结果:

输出
36
30
1e
十六进制是ff,十进制是255,八进制是377
2.220000
2.2
2.220000e+00
2.220e+00
2222.22
2222.222
2.2e+03
hello world
         hello world
hello world         
he
        he
he        
姓名:小明,年龄:13

3. f-string(推荐方式,Python 3.6+)

使用 "f-字符串" 进行格式化输出的基本格式:print(f'{表达式}')

python
name = '小明'
age = 13
print(f'姓名:{name},年龄:{age}')

# 设置小数位数
num = 3.1415926
print(f"π的值为:{num:.2f}")  # 保留两位小数 → 3.14

# 千位分隔符
big_number = 1234567890
print(f"The big number is {big_number:,}")
print(f"The big number is {big_number:_}")

# 字符串对齐
s = "Hello"
print(f"|{s:<10}|")  # 左对齐,总宽度为 10
print(f"|{s:>10}|")  # 右对齐,总宽度为 10
print(f"|{s:^10}|")  # 居中对齐,总宽度为 10

▶ 运行结果:

输出
姓名:小明,年龄:13
π的值为:3.14
The big number is 1,234,567,890
The big number is 1_234_567_890
|Hello     |
|     Hello|
|  Hello   |

4. format() 方法

format() 功能更强大,把字符串当成一个模板,通过传入的参数进行格式化,使用大括号 {} 作为特殊字符代替 %。用法有三种形式:不带编号带数字编号(可调换顺序)带关键字

python
print('{} {}'.format('hello', 'world'))   # 不带字段
# hello world
print('{0} {1}'.format('hello', 'world')) # 带数字编号
# hello world
print('{0} {1} {0}'.format('hello', 'world'))  # 打乱顺序
# hello world hello
print('{1} {1} {0}'.format('hello', 'world'))  # 打乱顺序
# world world hello
print('{a} {b} {a}'.format(b='hello', a='world'))  # 带关键字
# world hello world

▶ 运行结果:

输出
hello world
hello world
hello world hello
world world hello
world hello world
💡 默认情况下 Python 将结果输出到 IDLE 或标准控制台,实际上也可以重定向输出到指定文件中。