在Python中,format()
函数是一种用于格式化字符串的方法,它允许将变量的值插入到字符串中的特定位置。格式化字符串的位置由花括号 {}
标记出来,其中可以指定要插入的变量名、索引或表达式。
format()
函数的基本语法如下:
formatted_string = "字符串{}".format(值或变量)
下面是一些常见的用法示例:
- 字符串插入值:
name = "Alice" age = 25 message = "我的名字是{},年龄是{}岁。".format(name, age) print(message) # 输出:我的名字是Alice,年龄是25岁。
- 通过索引指定插入位置:
name = "Alice" age = 25 message = "我的名字是{1},年龄是{0}岁。".format(age, name) print(message) # 输出:我的名字是Alice,年龄是25岁。
- 通过变量名指定插入位置:
name = "Alice" age = 25 message = "我的名字是{name},年龄是{age}岁。".format(name=name, age=age) print(message) # 输出:我的名字是Alice,年龄是25岁。
- 格式化数值的显示:
pi = 3.14159 formatted_pi = "圆周率:{:.2f}".format(pi) print(formatted_pi) # 输出:圆周率:3.14
- 格式化日期和时间:
import datetime now = datetime.datetime.now() formatted_time = "当前时间:{:%Y-%m-%d %H:%M:%S}".format(now) print(formatted_time) # 输出:当前时间:2021-07-01 14:30:00
format()
函数还支持更多高级的用法,如对齐、填充等,可以参考官方文档以获取更多详细信息。