Python 占位符详细笔记

1. % 格式化(旧式格式化)

1.1 基本用法

name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)  # 输出: Name: Alice, Age: 30

1.2 数字格式化

pi = 3.141592653589793
formatted_string = "Pi: %f" % pi
print(formatted_string)  # 输出: Pi: 3.141593

formatted_string = "Pi: %.2f" % pi
print(formatted_string)  # 输出: Pi: 3.14
  • %f 表示浮点数,默认显示六位小数
  • %.2f 表示保留两位小数

1.3 填充和对齐

formatted_string = "|%10s|" % "test"  # 右对齐,宽度为 10
print(formatted_string)  # 输出: |      test|

formatted_string = "|%-10s|" % "test"  # 左对齐,宽度为 10
print(formatted_string)  # 输出: |test      |
  • %10s 表示字段宽度为 10,右对齐
  • %-10s 表示字段宽度为 10,左对齐

2. str.format() 方法(较新格式化)

2.1 基本用法

name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)  # 输出: Name: Bob, Age: 25

2.2 位置和关键字参数

formatted_string = "Name: {0}, Age: {1}".format(name, age)
print(formatted_string)  # 输出: Name: Bob, Age: 25

formatted_string = "Name: {name}, Age: {age}".format(name="Carol", age=28)
print(formatted_string)  # 输出: Name: Carol, Age: 28
  • {0}{1} 指定位置参数的索引
  • {name}{age} 使用关键字参数

2.3 格式化数字

pi = 3.141592653589793
formatted_string = "Pi: {:.2f}".format(pi)
print(formatted_string)  # 输出: Pi: 3.14

2.4 对齐和填充

formatted_string = "|{:10}|".format("test")  # 右对齐,宽度为 10
print(formatted_string)  # 输出: |      test|

formatted_string = "|{:<10}|".format("test")  # 左对齐,宽度为 10
print(formatted_string)  # 输出: |test      |
  • {:10} 表示字段宽度为 10,右对齐
  • {:10} 默认右对齐,{:<10} 左对齐

2.5 字符串长度和精度

text = "Hello"
formatted_string = "{:.3}".format(text)  # 截取前三个字符
print(formatted_string)  # 输出: Hel
  • {:.3} 表示截取前三个字符

3. f-strings (格式化字符串字面量)

3.1 基本用法

name = "Dave"
age = 40
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)  # 输出: Name: Dave, Age: 40

3.2 格式化数字

pi = 3.141592653589793
formatted_string = f"Pi: {pi:.2f}"
print(formatted_string)  # 输出: Pi: 3.14

3.3 表达式和计算

x = 10
y = 5
formatted_string = f"Sum of {x} and {y} is {x + y}"
print(formatted_string)  # 输出: Sum of 10 and 5 is 15

3.4 对齐和填充

formatted_string = f"|{name:>10}|"
print(formatted_string)  # 输出: |       Dave|

formatted_string = f"|{name:<10}|"
print(formatted_string)  # 输出: |Dave      |
  • {:>10} 右对齐,宽度为 10
  • {:10} 默认右对齐,{:<10} 左对齐

3.5 嵌套字段

value = 123
formatted_string = f"Value is {value:{10}}"
print(formatted_string)  # 输出: Value is        123
  • value:{10} 表示字段宽度为 10

4. 字符串模板(string.Template 类)

4.1 基本用法

from string import Template

template = Template("Name: $name, Age: $age")
formatted_string = template.substitute(name="Eva", age=22)
print(formatted_string)  # 输出: Name: Eva, Age: 22

4.2 替换占位符

template = Template("Hello, $name! Welcome to $place.")
formatted_string = template.substitute(name="John", place="Python Land")
print(formatted_string)  # 输出: Hello, John! Welcome to Python Land.

4.3 字符串中包含 $ 符号

template = Template("The price is $$100")
formatted_string = template.substitute()
print(formatted_string)  # 输出: The price is $100
  • $$ 用于插入实际的 $ 符号

4.4 默认值和可选参数

template = Template("Name: $name, Age: ${age}")
formatted_string = template.safe_substitute(name="Julia")
print(formatted_string)  # 输出: Name: Julia, Age: ${age}
  • safe_substitute 用于在缺少值时不抛出异常,使用原始占位符替代

5. 选择合适的格式化方式

5.1 % 格式化

  • 优点:简洁,老旧代码兼容
  • 缺点:功能有限,阅读性较差

5.2 str.format()

  • 优点:功能强大,易于阅读
  • 缺点:语法较长,尤其是在复杂格式化时

5.3 f-strings

  • 优点:语法简洁,性能优越,支持嵌套表达式
  • 缺点:仅支持 Python 3.6 及以上

5.4 string.Template

  • 优点:安全性高,适合用户输入
  • 缺点:功能有限,不支持复杂格式化

总结

  在 Python 中,可以根据具体需求选择不同的格式化方法。% 格式化适用于简单的场景,str.format() 提供了更多的灵活性和功能,而 f-strings 是现代 Python 中推荐的格式化方式,因为它简洁且性能优越。string.Template 则适用于需要处理用户输入的情况。

  • 16
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生_Lee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值