format() 是 Python 中用于字符串格式化的强大工具,它提供了灵活的方式来格式化字符串。以下是 format() 方法的全面介绍。
1. 基本用法
1 2 3 4 5 6 7 8 9
| # 位置参数 print("{} {}".format("Hello", "World")) # 输出: Hello World
# 索引参数 print("{1} {0}".format("World", "Hello")) # 输出: Hello World
# 命名参数 print("{name} is {age} years old".format(name="Alice", age=25)) # 输出: Alice is 25 years old
|
2. 数字格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| # 保留小数位数 print("{:.2f}".format(3.1415926)) # 输出: 3.14
# 带符号显示 print("{:+.2f}".format(3.1415926)) # 输出: +3.14 print("{:+.2f}".format(-3.1415926)) # 输出: -3.14
# 不带小数位 print("{:.0f}".format(3.1415926)) # 输出: 3
# 千位分隔符 print("{:,}".format(1000000)) # 输出: 1,000,000
# 百分比格式 print("{:.2%}".format(0.25)) # 输出: 25.00%
# 科学计数法 print("{:.2e}".format(1000000)) # 输出: 1.00e+06
|
3. 对齐与填充
1 2 3 4 5 6 7 8 9 10 11 12
| # 右对齐,宽度10 print("{:>10}".format("Hello")) # 输出: Hello
# 左对齐,宽度10 print("{:<10}".format("Hello")) # 输出: Hello
# 居中对齐,宽度10 print("{:^10}".format("Hello")) # 输出: Hello
# 填充字符 print("{:*^10}".format("Hello")) # 输出: **Hello*** print("{:0<10}".format(3.14)) # 输出: 3.14000000
|
4. 进制转换
1 2 3 4 5 6 7 8 9 10 11
| # 二进制 print("{:b}".format(10)) # 输出: 1010
# 八进制 print("{:o}".format(10)) # 输出: 12
# 十六进制(小写) print("{:x}".format(255)) # 输出: ff
# 十六进制(大写) print("{:X}".format(255)) # 输出: FF
|
5. 特殊格式化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| # 访问对象属性 class Person: def __init__(self, name, age): self.name = name self.age = age
p = Person("Bob", 30) print("{p.name} is {p.age} years old".format(p=p)) # 输出: Bob is 30 years old
# 访问列表/字典元素 data = ["Python", "Java", "C++"] print("{0[0]} is better than {0[1]}".format(data)) # 输出: Python is better than Java
info = {"name": "Alice", "age": 25} print("{name} is {age} years old".format(**info)) # 输出: Alice is 25 years old
|
6. 高级用法
1 2 3 4 5 6 7 8 9 10
| # 动态格式化 width = 10 precision = 2 value = 3.1415926 print("{:{width}.{prec}f}".format(value, width=width, prec=precision)) # 输出: 3.14
# 转义大括号 print("{{}}".format()) # 输出: {} print("{{{}}}".format("Hello")) # 输出: {Hello}
|
7. 与 % 格式化的比较
传统 % 格式化 vs format() 方法:
1 2 3 4 5
| # 传统 % 格式化 print("%s is %d years old" % ("Alice", 25))
# format() 方法 print("{} is {} years old".format("Alice", 25))
|
format() 方法比 % 格式化更强大、更灵活,是 Python 官方推荐的字符串格式化方式。
8. 实际应用示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| # 表格格式化输出 data = [ ("Python", 3.9, 1991), ("Java", 15, 1995), ("C++", 20, 1985) ]
for lang, ver, year in data: print("{:<10} | {:>5.1f} | {:>4}".format(lang, ver, year))
# 输出: # Python | 3.9 | 1991 # Java | 15.0 | 1995 # C++ | 20.0 | 1985
# 格式化日志消息 log = "{level:^8} | {time} | {message}".format( level="ERROR", time="2023-05-15 14:30", message="File not found" ) print(log) # 输出: ERROR | 2023-05-15 14:30 | File not found
|
format() 方法提供了极其灵活的字符串格式化能力,几乎可以满足所有常见的格式化需求。对于 Python 3.6+ 版本,f-string 是更简洁的选择,但在需要动态格式化或兼容旧版本时,format() 仍然是很好的选择。
https://mp.weixin.qq.com/s/MuYsrUvJT3toXvXEw2BdnA?scene=1