字符串格式化

字符串格式化就是把变量"嵌入"到字符串中,生成想要的输出格式。MicroPython 支持三种方式。


f-string 格式化(推荐)

Python 3.6+ 引入,最简洁直观,在字符串前加 f,用 {} 包裹变量。

name = 'Pico'
temp = 25.6

print(f'设备: {name}')           # 输出:设备: Pico
print(f'温度: {temp}°C')         # 输出:温度: 25.6°C
print(f'{name} 温度 {temp}°C')   # 输出:Pico 温度 25.6°C

f-string 格式化控制

# 保留小数位数 :.nf
temp = 25.6789
print(f'温度: {temp:.1f}°C')     # 输出:温度: 25.7°C(保留1位)
print(f'温度: {temp:.2f}°C')     # 输出:温度: 25.68°C(保留2位)

# 整数补零 :0nd
num = 5
print(f'编号: {num:03d}')        # 输出:编号: 005(补零到3位)

# 宽度对齐
name = 'LED'
print(f'[{name:10}]')           # 输出:[LED       ](左对齐,宽度10)
print(f'[{name:>10}]')          # 输出:[       LED](右对齐,宽度10)
print(f'[{name:^10}]')          # 输出:[   LED    ](居中,宽度10)

# 百分比
ratio = 0.856
print(f'进度: {ratio:.1%}')     # 输出:进度: 85.6%

format() 方法格式化

用 {} 占位,通过 .format() 传入值。

name = 'Pico'
temp = 25.6

print('设备: {}'.format(name))              # 输出:设备: Pico
print('温度: {}°C'.format(temp))            # 输出:温度: 25.6°C
print('{} 温度 {}°C'.format(name, temp))    # 输出:Pico 温度 25.6°C

# 带索引,可重复使用
print('{0} 说: {1}, {0} 又说: {1}'.format('我', '你好'))
# 输出:我说: 你好, 我又说: 你好

# 带关键字
print('{name} 今年 {age} 岁'.format(name='小明', age=15))
# 输出:小明 今年 15 岁

# 格式控制
print('{:.2f}'.format(3.14159))             # 输出:3.14
print('{:03d}'.format(5))                   # 输出:005

% 格式化(老式写法)

类似 C 语言 printf,了解即可。

name = 'Pico'
temp = 25.6

print('设备: %s' % name)                    # 输出:设备: Pico
print('温度: %.1f°C' % temp)                # 输出:温度: 25.6°C
print('%s 温度 %.1f°C' % (name, temp))      # 输出:Pico 温度 25.6°C

# 常用占位符
# %s 字符串
# %d 整数
# %f 浮点数
# %x 十六进制

三种方式对比

方式 优点 缺点
f-string 简洁直观,可读性好 Python 3.6+
format() 兼容性好,灵活 稍显冗长
% 格式化 C 语言风格,老代码常见 可读性差,不推荐新项目

实际应用:传感器数据显示

from machine import ADC, Pin
import time

adc = ADC(Pin(26))

def read_voltage():
    value = adc.read_u16()
    voltage = value * 3.3 / 65535
    return voltage

while True:
    v = read_voltage()
    percent = v / 3.3 * 100

    # f-string 格式化输出
    print(f'电压: {v:.2f}V ({percent:.1f}%)')

    # 或者用 format()
    # print('电压: {:.2f}V ({:.1f}%)'.format(v, percent))

    time.sleep(1)

实际应用:进度条显示

import time

def show_progress(current, total):
    percent = current / total * 100
    bar_len = 20
    filled = int(bar_len * current / total)
    bar = '█' * filled + '░' * (bar_len - filled)
    print(f'\r[{bar}] {percent:.1f}%', end='')

for i in range(101):
    show_progress(i, 100)
    time.sleep(0.05)
print()  # 换行

注意事项

  • 推荐使用 f-string,代码最清晰
  • 格式化符号 : 后面是格式控制,前面是变量
  • \r 配合 end='' 可实现同行刷新