python中format函数的用法是什么

avatar
作者
筋斗云
阅读量:0

在Python中,format()函数是一种用于格式化字符串的方法,它允许将变量的值插入到字符串中的特定位置。格式化字符串的位置由花括号 {} 标记出来,其中可以指定要插入的变量名、索引或表达式。

format()函数的基本语法如下:

formatted_string = "字符串{}".format(值或变量) 

下面是一些常见的用法示例:

  1. 字符串插入值:
name = "Alice" age = 25 message = "我的名字是{},年龄是{}岁。".format(name, age) print(message) # 输出:我的名字是Alice,年龄是25岁。 
  1. 通过索引指定插入位置:
name = "Alice" age = 25 message = "我的名字是{1},年龄是{0}岁。".format(age, name) print(message) # 输出:我的名字是Alice,年龄是25岁。 
  1. 通过变量名指定插入位置:
name = "Alice" age = 25 message = "我的名字是{name},年龄是{age}岁。".format(name=name, age=age) print(message) # 输出:我的名字是Alice,年龄是25岁。 
  1. 格式化数值的显示:
pi = 3.14159 formatted_pi = "圆周率:{:.2f}".format(pi) print(formatted_pi) # 输出:圆周率:3.14 
  1. 格式化日期和时间:
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()函数还支持更多高级的用法,如对齐、填充等,可以参考官方文档以获取更多详细信息。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!