目录

  • 1. `%` 格式化(旧式格式化)
  • 1.1 基本用法
  • 1.2 数字格式化
  • 1.3 填充和对齐
  • 2. `str.format()` 方法(较新格式化)
  • 2.1 基本用法
  • 2.2 位置和关键字参数
  • 2.3 格式化数字
  • 2.4 对齐和填充
  • 2.5 字符串长度和精度
  • 3. f-strings (格式化字符串字面量)
  • 3.1 基本用法
  • 3.2 格式化数字
  • 3.3 表达式和计算
  • 3.4 对齐和填充
  • 3.5 嵌套字段
  • 4. 字符串模板(`string.Template` 类)
  • 4.1 基本用法
  • 4.2 替换占位符
  • 4.3 字符串中包含 `$` 符号
  • 4.4 默认值和可选参数
  • 5. 选择合适的格式化方式
  • 5.1 `%` 格式化
  • 5.2 `str.format()`
  • 5.3 f-strings
  • 5.4 `string.Template`
  • 总结
  • 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 则适用于需要处理用户输入的情况。

    作者:浮生_Lee

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python 占位符详细笔记

    发表回复