首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Python format()函数高级字符串格式化详解

Python format()函数高级字符串格式化详解

原创
作者头像
用户3672714
发布于 2025-07-13 10:55:37
发布于 2025-07-13 10:55:37
4930
举报

1. 基本用法:插入变量

最基础的用法是通过 {} 占位符插入变量。

示例:

代码语言:javascript
复制
name = "Alice"age = 30greeting = "My name is {}, and I am {} years old.".format(name, age)print(greeting)  # 输出 "My name is Alice, and I am 30 years old."php157 Bytes© 菜鸟-创作你的创作

2. 位置参数与关键字参数

你可以通过位置参数或者关键字参数来控制格式化的值。

位置参数:

代码语言:javascript
复制
greeting = "I am {} years old, and my name is {}".format(age, name)print(greeting)  # 输出 "I am 30 years old, and my name is Alice"php131 Bytes© 菜鸟-创作你的创作

关键字参数:

代码语言:javascript
复制
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."php149 Bytes© 菜鸟-创作你的创作

3. 字段顺序和重新排序

通过 format(),你可以自由调整字段的顺序。

示例:

代码语言:javascript
复制
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"php134 Bytes© 菜鸟-创作你的创作

在这个例子中,{1} 表示 age,{0} 表示 name,字段顺序是重新排序的。


4. 格式化数字

format() 函数支持格式化数字,包括设置精度、对齐、填充、逗号分隔符等。

数字精度:

代码语言:javascript
复制
pi = 3.1415926535formatted = "Pi to 2 decimal places: {:.2f}".format(pi)print(formatted)  # 输出 "Pi to 2 decimal places: 3.14"php127 Bytes© 菜鸟-创作你的创作

使用逗号分隔千位:

代码语言:javascript
复制
number = 1000000formatted = "Formatted number: {:,}".format(number)print(formatted)  # 输出 "Formatted number: 1,000,000"php121 Bytes© 菜鸟-创作你的创作

补充零:

代码语言:javascript
复制
number = 5formatted = "Padded number: {:05d}".format(number)print(formatted)  # 输出 "Padded number: 00005"php107 Bytes© 菜鸟-创作你的创作

对齐和填充:

你可以控制文本的对齐和填充,通常在输出表格数据时很有用。

  • 默认左对齐:
代码语言:javascript
复制
text = "{:<10}".format("left")print(f"'{text}'")  # 输出 'left      'php68 Bytes© 菜鸟-创作你的创作
  • 右对齐:
代码语言:javascript
复制
text = "{:>10}".format("right")print(f"'{text}'")  # 输出 '     right'php69 Bytes© 菜鸟-创作你的创作
  • 居中对齐:
代码语言:javascript
复制
text = "{:^10}".format("center")print(f"'{text}'")  # 输出 '  center  'php70 Bytes© 菜鸟-创作你的创作
  • 填充字符:
代码语言:javascript
复制
text = "{:*^10}".format("star")print(f"'{text}'")  # 输出 '**star****'php69 Bytes© 菜鸟-创作你的创作

https://www.52runoob.com/archives/3459

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 1. 基本用法:插入变量
    • 示例:
  • 2. 位置参数与关键字参数
    • 位置参数:
    • 关键字参数:
  • 3. 字段顺序和重新排序
    • 示例:
  • 4. 格式化数字
    • 数字精度:
    • 使用逗号分隔千位:
    • 补充零:
    • 对齐和填充:
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档