pin_drop当前位置:知识文库 ❯ 图文

Python内置函数format()

一、format 函数概述

format() 是 Python 中强大的字符串格式化函数,用于将值格式化为指定的字符串表示形式。它提供了丰富的格式规范,可以控制数字精度、对齐方式、填充字符等。

  • 功能强大:支持复杂的格式规范和自定义格式

  • 类型安全:自动处理不同类型的数据转换

  • 可读性好:格式字符串清晰表达输出意图


二、基本语法

两种使用方式

代码示例

# 方式1:使用 format() 函数
result = format(value, format_spec)

# 方式2:使用字符串的 format() 方法
result = "template {}".format(value)

基本示例

代码示例

# format() 函数用法
print(format(3.14159, '.2f'))  # 输出: 3.14
print(format(42, '05d'))       # 输出: 00042
print(format('hello', '>10'))  # 输出:      hello

# 字符串 format() 方法
print("Name: {}, Age: {}".format("Alice", 30))
print("Name: {0}, Age: {1}".format("Bob", 25))
print("Name: {name}, Age: {age}".format(name="Charlie", age=35))

三、位置参数与关键字参数

位置参数

代码示例

# 自动编号(Python 3.1+)
print("{} {}".format("Hello", "World"))  # 输出: Hello World

# 显式编号
print("{0} {1}".format("First", "Second"))  # 输出: First Second
print("{1} {0}".format("Second", "First"))  # 输出: First Second

# 重复使用
print("{0} {0} {0}".format("Repeat"))  # 输出: Repeat Repeat Repeat

关键字参数

代码示例

# 使用关键字参数
print("{name} is {age} years old".format(name="Alice", age=30))

# 关键字可以重复使用
print("{name} {name} {name}".format(name="Bob"))

# 混合使用(不推荐)
print("{0} {name} {1}".format("First", "Second", name="Middle"))

四、格式规范详解

格式规范语法

代码示例

# 格式规范: [[fill]align][sign][#][0][width][,][.precision][type]

# fill: 填充字符(任意字符)
# align: 对齐方式(< 左对齐, > 右对齐, ^ 居中, = 填充在符号后)
# sign: 符号(+ 正数显示+, - 负数显示+, 空格 正数前加空格)
# width: 最小宽度
# precision: 精度(小数位数或最大字符数)
# type: 类型(d 整数, f 浮点数, s 字符串, x 十六进制等)

对齐与填充

代码示例

# 左对齐
print("{:<10}".format("left"))  # 输出: left      

# 右对齐
print("{:>10}".format("right"))  # 输出:      right

# 居中对齐
print("{:^10}".format("center"))  # 输出:   center  

# 使用自定义填充字符
print("{:*<10}".format("left"))   # 输出: left******
print("{:*>10}".format("right"))  # 输出: *****right
print("{:*^10}".format("center")) # 输出: **center**

五、数字格式化

整数格式化

代码示例

# 十进制
print("{:d}".format(42))      # 输出: 42
print("{:5d}".format(42))     # 输出:    42
print("{:05d}".format(42))    # 输出: 00042

# 二进制
print("{:b}".format(42))      # 输出: 101010

# 八进制
print("{:o}".format(42))      # 输出: 52

# 十六进制
print("{:x}".format(42))      # 输出: 2a
print("{:X}".format(42))      # 输出: 2A

# 带千分位逗号
print("{:,}".format(1234567)) # 输出: 1,234,567

浮点数格式化

代码示例

# 固定小数位数
print("{:.2f}".format(3.14159))   # 输出: 3.14
print("{:.4f}".format(3.14159))   # 输出: 3.1416

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

# 百分比
print("{:.2%}".format(0.1234))    # 输出: 12.34%

# 带符号
print("{:+.2f}".format(3.14))     # 输出: +3.14
print("{:+.2f}".format(-3.14))    # 输出: -3.14
print("{: .2f}".format(3.14))     # 输出:  3.14(正数前加空格)

六、字符串格式化

字符串对齐与截断

代码示例

# 字符串对齐
print("{:<10}".format("hello"))   # 输出: hello     
print("{:>10}".format("hello"))   # 输出:      hello
print("{:^10}".format("hello"))   # 输出:   hello   

# 字符串截断
print("{:.3}".format("hello"))    # 输出: hel
print("{:.3}".format("world"))    # 输出: wor

# 组合使用:截断并对齐
print("{:<10.3}".format("hello"))  # 输出: hel       
print("{:>10.3}".format("hello"))  # 输出:        hel

实际应用示例

代码示例

# 格式化表格
data = [
    ("Alice", 25, 85.5),
    ("Bob", 30, 92.0),
    ("Charlie", 35, 78.3)
]

print("{:<10} {:>5} {:>8}".format("Name", "Age", "Score"))
print("-" * 25)
for name, age, score in data:
    print("{:<10} {:>5} {:>8.1f}".format(name, age, score))

# 输出:
# Name       Age    Score
# -------------------------
# Alice       25     85.5
# Bob         30     92.0
# Charlie     35     78.3

七、f-string 对比

对比项 format() 方法 f-string
Python 版本 2.6+ 3.6+
语法 "{}".format(value) f"{value}"
可读性 较好 更好
性能 较慢 更快
动态模板 支持 不支持

代码示例

name = "Alice"
age = 30

# format() 方法
print("Name: {}, Age: {}".format(name, age))

# f-string(推荐)
print(f"Name: {name}, Age: {age}")

# 格式规范相同
print("{:.2f}".format(3.14159))  # 输出: 3.14
print(f"{3.14159:.2f}")          # 输出: 3.14

八、注意事项

注意1:在 Python 3.6+ 中,推荐使用 f-string 替代 format() 方法,因为它更简洁、可读性更好、性能更高。

注意2:如果需要动态构建格式模板(例如从配置文件读取),format() 方法仍然有用,因为模板可以在运行时确定。

注意3:使用 format() 函数(不是字符串方法)可以直接格式化单个值,例如 format(3.14, '.2f')


九、常见问题

常见问题

Q1: format() 和 % 格式化有什么区别?

format() 是 Python 推荐的现代格式化方式,功能更强大、语法更清晰。% 格式化是旧式语法,虽然仍支持,但不推荐在新代码中使用。

Q2: 如何在 format 中转义大括号?

使用双大括号转义:"{{}}".format() 输出 {}。例如:"{{name}}".format(name="Alice") 输出 {name}

Q3: 如何格式化日期时间?

使用 strftime() 方法:"{:%Y-%m-%d %H:%M}".format(datetime.now())。或者使用 f-string:f"{datetime.now():%Y-%m-%d}"

Q4: format() 可以格式化自定义对象吗?

可以。在类中定义 __format__() 方法即可自定义格式化行为。例如:def __format__(self, format_spec): return f"Custom: {self.value:{format_spec}}"


十、练习题

练习1

使用 format() 将浮点数 3.14159265 格式化为保留 3 位小数的字符串。

练习2

使用 format() 方法创建一个表格,包含姓名(左对齐,10字符宽)、年龄(右对齐,5字符宽)和分数(右对齐,8字符宽,保留1位小数)。

练习3

使用 format() 函数将整数 255 分别格式化为二进制、八进制和十六进制字符串。

标签: format函数 字符串格式化 数字格式化 Python基础 f-string

本文涉及AI创作

内容由AI创作,请仔细甄别

list快速访问

上一篇: Python eval exec函数 下一篇: Python getattr setattr hasattr用法

poll相关推荐