当前位置: 代码网 > it编程>前端脚本>Python > Python字符串格式化之format()方法详解

Python字符串格式化之format()方法详解

2026年09月15日 Python 我要评论
一、开篇:百分号的升级版今天的主角是 str.format()——python 2.6引入的"二代"格式化方式。它在功能上远超百分号,曾是python官方推

一、开篇:百分号的升级版

今天的主角是 str.format()——python 2.6引入的"二代"格式化方式。它在功能上远超百分号,曾是python官方推荐的字符串格式化方法,直到f-string的出现。

虽然f-string现在更受欢迎,但 format() 有一个不可替代的优势:模板可以预先定义,然后反复使用。这在配置文件、邮件模板、日志格式等场景中至关重要。另外,很多老项目的代码都是用 format() 写的,你需要能读懂和修改它们。

二、format() 的基本语法

2.1 三种调用方式

# 方式一:按位置(最常用)
text = '{} {} {}'.format('python', '是', '优雅的')
print(text)  # python 是 优雅的

# 方式二:按索引(从0开始)
text = '{0} {1} {0}'.format('hello', 'world')
print(text)  # hello world hello

# 方式三:按名称
text = '{name}今年{age}岁'.format(name='小明', age=25)
print(text)  # 小明今年25岁

2.2 占位符 {}

# 空花括号——按顺序填空
print('{}, {}, {}'.format('a', 'b', 'c'))   # a, b, c

# 带索引——指定使用哪个参数(可以重复、打乱顺序)
print('{2}, {0}, {1}'.format('a', 'b', 'c'))   # c, a, b
print('{0}{0}{0}'.format('哈'))                 # 哈哈哈

# 带名称——最清晰的写法
print('{title}:《{name}》'.format(title='书籍', name='python入门'))
# 书籍:《python入门》

三、格式化控制

3.1 对齐与宽度

# 基本格式:{:[填充字符][对齐方式][宽度]}

# 右对齐(默认,数字常用)
print('{:>10}'.format('hello'))    # '     hello'

# 左对齐(文本常用)
print('{:<10}'.format('hello'))    # 'hello     '

# 居中对齐
print('{:^10}'.format('hello'))    # '  hello   '

# 带填充字符
print('{:*>10}'.format('hello'))   # '*****hello'
print('{:*<10}'.format('hello'))   # 'hello*****'
print('{:*^10}'.format('hello'))   # '**hello***'

# 数字的填充(常用补零)
print('{:0>5d}'.format(42))        # '00042'
print('{:0>8d}'.format(2024))      # '00002024'

3.2 数字格式化

# 整数
print('{:d}'.format(42))            # 42
print('{:5d}'.format(42))           # '   42'(右对齐,宽度5)
print('{:+d}'.format(42))           # +42(显示正号)
print('{:+d}'.format(-42))          # -42
print('{:,}'.format(1234567890))    # 1,234,567,890(千分位)

# 浮点数
pi = 3.14159265
print('{:f}'.format(pi))            # 3.141593(默认6位)
print('{:.2f}'.format(pi))          # 3.14
print('{:.4f}'.format(pi))          # 3.1416
print('{:10.2f}'.format(pi))        # '      3.14'(宽度10,2位小数)
print('{:010.2f}'.format(pi))       # '0000003.14'(补零)

# 科学计数法
print('{:e}'.format(1234567))       # 1.234567e+06
print('{:.2e}'.format(1234567))     # 1.23e+06
print('{:e}'.format(1234567))       # 1.234567e+06

# 百分比
print('{:.1%}'.format(0.8567))      # 85.7%
print('{:.2%}'.format(0.12345))     # 12.35%

# 进制转换
print('{:b}'.format(255))           # 11111111(二进制)
print('{:o}'.format(255))           # 377(八进制)
print('{:x}'.format(255))           # ff(十六进制小写)
print('{:x}'.format(255))           # ff(十六进制大写)
print('{:#x}'.format(255))          # 0xff(带前缀)
print('{:#b}'.format(255))          # 0b11111111

3.3 完整的格式化规范

format()的完整格式说明符语法:

{:[填充字符][对齐][符号][#][0][宽度][分组选项][.精度][类型]}
# 逐一演示
number = 1234567.89

# 填充字符 + 对齐 + 宽度
print('{:*>15}'.format('标题'))     # '************标题'

# 符号:+ 强制显示正号,- 只显示负号(默认),空格 正数前留空格
print('{:+}'.format(42))              # +42
print('{:-}'.format(42))              # 42
print('{: }'.format(42))              # ' 42'
print('{: }'.format(-42))             # -42

# 分组选项:, 或 _ 作为千分位
print('{:,}'.format(1234567))         # 1,234,567
print('{:_}'.format(1234567))         # 1_234_567

# 全部组合:填充补零+符号+千分位+精度
print('{:0=+15,.2f}'.format(number))
# '+001,234,567.89'

四、高级用法

4.1 访问列表和字典

# 访问列表元素(索引)
fruits = ['苹果', '香蕉', '橘子']
print('我喜欢吃{0[0]}、{0[1]}和{0[2]}'.format(fruits))
# 我喜欢吃苹果、香蕉和橘子

# 访问字典元素
person = {'name': '小明', 'age': 25, 'city': '北京'}
print('{name},{age}岁,来自{city}'.format(**person))
# 小明,25岁,来自北京
# **person 将字典解包为关键字参数

# 直接使用字典键
print('{0[name]}今年{0[age]}岁'.format(person))

# 访问对象属性
class point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = point(3, 5)
print('点坐标:({0.x}, {0.y})'.format(p))  # 点坐标:(3, 5)

4.2 嵌套字段

# 格式化参数可以动态指定
# 例如:宽度和精度从变量中读取

width = 10
precision = 3

# 用嵌套花括号
print('{:{}.{}f}'.format(3.14159, width, precision))
# '     3.142'

# 更清晰的写法
print('{value:{width}.{precision}f}'.format(
    value=3.14159, width=10, precision=3
))

# 动态选择格式化类型
def format_value(value, fmt_type):
    """根据类型动态格式化值"""
    return '{0:{1}}'.format(value, fmt_type)

print(format_value(255, 'x'))   # ff
print(format_value(255, 'b'))   # 11111111
print(format_value(255, '#x'))  # 0xff
print(format_value(0.85, '.1%')) # 85.0%

4.3 日期时间格式化

from datetime import datetime

now = datetime(2025, 5, 30, 14, 30, 45)

# 使用datetime对象的strftime在format中
print('{:%y-%m-%d %h:%m:%s}'.format(now))
# 2025-05-30 14:30:45

print('{:%y年%m月%d日 %h时%m分}'.format(now))
# 2025年05月30日 14时30分

# 各种日期格式
formats = [
    '{:%y-%m-%d}',
    '{:%y/%m/%d}',
    '{:%b %d, %y}',
    '{:%a}',
    '{:%h:%m:%s}',
]
for fmt in formats:
    print(fmt.format(now))

4.4 转义花括号

# 如何在format字符串中输出花括号本身?
# 答案:双写花括号

print('{{hello}}'.format())          # {hello}
print('{{0}} 的值是 {0}'.format(42))  # {0} 的值是 42
print('{{{0}}}'.format('python'))    # {python}

# 在json模板中很有用
json_template = '{{"name": "{name}", "age": {age}}}'
result = json_template.format(name='小明', age=25)
print(result)  # {"name": "小明", "age": 25}

五、format() 实战应用

5.1 表格打印

def print_table(headers, rows):
    """使用format打印对齐的表格"""
    # 计算每列的宽度
    col_widths = [len(h) for h in headers]

    # 格式化行的单元格
    formatted_rows = []
    for row in rows:
        formatted = [str(cell) for cell in row]
        formatted_rows.append(formatted)
        for i, cell in enumerate(formatted):
            col_widths[i] = max(col_widths[i], len(cell))

    # 构建格式字符串
    format_str = ' | '.join('{:<%d}' % w for w in col_widths)

    # 打印表头
    print(format_str.format(*headers))
    # 打印分隔线
    print('-+-'.join('-' * w for w in col_widths))
    # 打印数据行
    for row in formatted_rows:
        print(format_str.format(*row))


headers = ['姓名', '年龄', '城市', '职业']
rows = [
    ('小明', 25, '北京', '软件工程师'),
    ('小红', 23, '上海', 'ui设计师'),
    ('小刚', 26, '广州', '数据分析师'),
]

print_table(headers, rows)

5.2 生成sql语句

def build_select_query(table, columns=none, where=none, order_by=none, limit=none):
    """用format构建sql查询"""
    if columns:
        col_str = ', '.join(columns)
    else:
        col_str = '*'

    query = 'select {cols} from {table}'.format(cols=col_str, table=table)

    if where:
        conditions = ' and '.join('{k} = %({k})s'.format(k=k) for k in where)
        query += ' where ' + conditions

    if order_by:
        query += ' order by ' + order_by

    if limit:
        query += ' limit {:d}'.format(limit)

    return query


query = build_select_query(
    'users',
    columns=['id', 'name', 'email'],
    where=['status', 'role'],
    order_by='created_at desc',
    limit=10
)
print(query)

5.3 进度条

import time

def progress_bar(total, prefix='', suffix='', length=50):
    """使用format的动态宽度显示进度条"""

    def print_progress(iteration):
        percent = '{:.1f}'.format(100 * iteration / total)
        filled = int(length * iteration // total)
        bar = '█' * filled + '-' * (length - filled)
        print('\r{} |{}| {}% {}'.format(prefix, bar, percent, suffix),
              end='', flush=true)

    print_progress(0)
    for i in range(1, total + 1):
        time.sleep(0.02)
        print_progress(i)
    print()


progress_bar(100, prefix='下载中:', suffix='完成', length=40)

六、format() 的性能

import time

name = 'python'
version = 3.12
year = 2025

# 三种方式性能对比(执行100万次)

# % 格式化
start = time.perf_counter()
for _ in range(1000000):
    result = '%s %s 发布于 %d' % (name, version, year)
elapsed_pct = time.perf_counter() - start
print(f'% 格式化:{elapsed_pct:.3f}秒')

# format()
start = time.perf_counter()
for _ in range(1000000):
    result = '{} {} 发布于 {}'.format(name, version, year)
elapsed_format = time.perf_counter() - start
print(f'format(): {elapsed_format:.3f}秒')

# f-string (最快)
start = time.perf_counter()
for _ in range(1000000):
    result = f'{name} {version} 发布于 {year}'
elapsed_f = time.perf_counter() - start
print(f'f-string:{elapsed_f:.3f}秒')

💡 性能排序:f-string > %格式化 > format()。但在绝大多数场景下,这个性能差异可以忽略不计。可读性比这点性能重要得多。

七、format() vs f-string:何时该用format()

虽然f-string更简洁更快,但以下场景还是得用(或更适合用)format():

# 场景一:模板复用
# 你需要多次使用同一个模板填充不同的值
template = '尊敬的{name},您的订单{order_id}已{status}。'

messages = [
    template.format(name='小明', order_id='001', status='发货'),
    template.format(name='小红', order_id='002', status='处理中'),
    template.format(name='小刚', order_id='003', status='完成'),
]
for msg in messages:
    print(msg)

# 场景二:配置文件中的模板
# 从配置文件读取模板字符串
email_template = """
hello {username},

your account balance is ${balance:.2f}.
last login: {last_login:%y-%m-%d}

best regards,
{company}
"""

# 在运行时填充
email = email_template.format(
    username='小明',
    balance=1520.5,
    last_login=datetime.now(),
    company='python学习平台'
)
print(email)

# 场景三:动态构建格式字符串
# 用户可以选择显示格式
def format_number(number, style='decimal'):
    formats = {
        'decimal':   '{:,}',
        'scientific': '{:.2e}',
        'hex':       '{:#x}',
        'binary':    '{:#b}',
        'percent':   '{:.2%}',
    }
    fmt_string = formats.get(style, '{}')
    return fmt_string.format(number)

# 场景四:需要支持python 3.5及以下版本
# f-string是python 3.6引入的

八、本篇小结

str.format() 是功能丰富的字符串格式化方式:

  1. 三种传参方式:按位置{}、按索引{0}、按名称{name}
  2. 对齐与填充{:<10}左对齐、{:>10}右对齐、{:^10}居中、{:*^10}带填充
  3. 数字格式化{:.2f}小数位、{:,}千分位、{:b}二进制、{:.1%}百分比
  4. 访问容器{0[0]}访问列表、{name}访问字典
  5. 模板复用:format()最独特的优势——模板可预定义重复使用

f-string是新代码的首选,但理解format()对于阅读和维护代码库至关重要。

以上就是python字符串格式化之format()方法详解的详细内容,更多关于python字符串格式化format()方法的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com