Python中如何进行字符串的格式化输出?

在 Python 中,有多种方式可以进行字符串的格式化输出,下面为你详细介绍常见的几种方法。

1. 旧式字符串格式化(% 操作符)

这是 Python 早期就支持的字符串格式化方式,使用 % 操作符结合不同的格式化符号来实现。

基本语法

"格式化字符串" % 值或值的元组

常用格式化符号

  • %s:用于格式化字符串。
  • %d:用于格式化整数。
  • %f:用于格式化浮点数。

示例

# 格式化字符串
name = "Alice"
print("My name is %s." % name)

# 格式化整数
age = 25
print("I am %d years old." % age)

# 格式化浮点数
height = 1.65
print("My height is %.2f meters." % height)  # %.2f 表示保留两位小数

# 格式化多个值
print("My name is %s, and I am %d years old." % (name, age))

2. 新式字符串格式化(str.format() 方法)

str.format() 是 Python 2.6 及以上版本引入的一种更灵活、更强大的字符串格式化方式。

基本语法

"格式化字符串".format(值1, 值2, ...)

位置参数

可以通过位置来指定要插入的值。
print("My name is {}, and I am {} years old.".format("Bob", 30))

关键字参数

使用关键字来指定要插入的值。
 
print("My name is {name}, and I am {age} years old.".format(name="Charlie", age=35))

索引参数

可以通过索引来指定要插入的值的位置。
 
print("My name is {1}, and I am {0} years old.".format(40, "David"))

格式化数值

可以对数值进行格式化,如指定宽度、精度等。
 
# 指定宽度和精度
print("The value is {:.2f}".format(3.14159))  # 保留两位小数

3. f - 字符串(格式化字符串字面值,Python 3.6+)

f - 字符串是 Python 3.6 及以上版本引入的一种简洁且直观的字符串格式化方式,在字符串前加 f 或 F,并在 {} 中直接使用变量名。

基本语法

 
f"包含 {变量名} 的字符串"

示例

name = "Eve"
age = 22
print(f"My name is {name}, and I am {age} years old.")

# 格式化数值
height = 1.72
print(f"My height is {height:.2f} meters.")  # 保留两位小数

4. string.Template 类

string.Template 类提供了一种简单的字符串替换机制,使用 $ 符号来标识变量。

基本语法

from string import Template

template = Template("格式化字符串")
result = template.substitute(变量名=值)

示例

from string import Template

name = "Frank"
age = 28
template = Template("My name is $name, and I am $age years old.")
print(template.substitute(name=name, age=age))

总结

  • 旧式字符串格式化(% 操作符):语法简单,但不够灵活,适合简单的格式化需求。
  • 新式字符串格式化(str.format() 方法):功能强大,支持位置参数、关键字参数、索引参数等多种方式,适用于各种复杂的格式化场景。
  • f - 字符串:语法简洁,直观易用,性能较高,是 Python 3.6 及以上版本推荐使用的格式化方式。
  • string.Template 类:语法简单,安全性高,适合需要从外部获取模板字符串的场景。

posted on   阿陶学长  阅读(136)  评论(0编辑  收藏  举报

(评论功能已被禁用)
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示