Python中的格式化输出详解

Python 提供了多种格式化输出的方法,常见的有以下几种:

  1. 百分号(%)格式化
  2. str.format() 方法
  3. f-string(格式化字符串字面量)
  4. 模板字符串

每种方法都有其独特的用法和适用场景。下面我们逐一详细讲解并举例说明。

1. 百分号(%)格式化

这种方法类似于 C 语言中的 printf 格式,使用百分号(%)作为占位符。

用法
  • %s:字符串
  • %d:整数
  • %f:浮点数
  • %%:百分号
  • 示例
    name = "Alice"
    age = 30
    height = 1.75
    
    # 字符串格式化
    print("My name is %s." % name)
    # 输出: My name is Alice.
    
    # 整数格式化
    print("I am %d years old." % age)
    # 输出: I am 30 years old.
    
    # 浮点数格式化
    print("My height is %.2f meters." % height)
    # 输出: My height is 1.75 meters.
    
    # 百分号
    percentage = 99
    print("Success rate: %d%%" % percentage)
    # 输出: Success rate: 99%
    

    2. str.format() 方法

    str.format() 方法使用大括号 {} 作为占位符,可以通过位置和名称进行格式化。

    用法
  • {}:位置占位符
  • {0}:位置参数
  • {name}:关键字参数
  • :.2f:保留两位小数
  • 示例
    name = "Alice"
    age = 30
    height = 1.75
    
    # 位置占位符
    print("My name is {}.".format(name))
    # 输出: My name is Alice.
    
    # 位置参数
    print("I am {0} years old. My name is {0}.".format(name))
    # 输出: I am Alice years old. My name is Alice.
    
    # 关键字参数
    print("My name is {name}. I am {age} years old.".format(name=name, age=age))
    # 输出: My name is Alice. I am 30 years old.
    
    # 浮点数格式化
    print("My height is {:.2f} meters.".format(height))
    # 输出: My height is 1.75 meters.
    

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

    f-string(格式化字符串字面量)是 Python 3.6 引入的一种格式化字符串的方法。f-string 使用 fF 前缀,并在大括号 {} 中直接放入变量、表达式、函数调用等,可以动态生成字符串。f-string 提供了一种简洁、直观的方式来处理字符串格式化。

    基本用法
    name = "Alice"
    age = 30
    print(f"My name is {name} and I am {age} years old.")
    # 输出: My name is Alice and I am 30 years old.
    
    数字计算

    f-string 可以直接在大括号内进行数字计算。

    a = 5
    b = 3
    print(f"The sum of {a} and {b} is {a + b}.")
    # 输出: The sum of 5 and 3 is 8.
    
    print(f"{a} times {b} is {a * b}.")
    # 输出: 5 times 3 is 15.
    
    字符串连接

    f-string 支持直接在大括号内进行字符串连接。

    first_name = "Alice"
    last_name = "Smith"
    print(f"My full name is {first_name + ' ' + last_name}.")
    # 输出: My full name is Alice Smith.
    
    函数执行

    可以在 f-string 中调用函数,并将结果嵌入到字符串中。

    def greet(name):
        return f"Hello, {name}!"
    
    name = "Alice"
    print(f"Greeting: {greet(name)}")
    # 输出: Greeting: Hello, Alice!
    
    格式化选项

    f-string 支持各种格式化选项,例如数字的格式化(小数点、宽度等)。

    保留小数点
    value = 123.45678
    print(f"The value is {value:.2f}.")
    # 输出: The value is 123.46.
    
    数字填充和对齐
    num = 42
    print(f"Number: {num:04d}")
    # 输出: Number: 0042
    
    value = 3.14159
    print(f"Pi: {value:<10.2f}")
    # 输出: Pi: 3.14      
    
    嵌套表达式

    f-string 可以嵌套更复杂的表达式。

    names = ["Alice", "Bob", "Charlie"]
    print(f"First name: {names[0]}")
    # 输出: First name: Alice
    
    print(f"Upper case name: {names[1].upper()}")
    # 输出: Upper case name: BOB
    
    多行 f-string

    可以使用三引号定义多行 f-string,使其更具可读性。

    name = "Alice"
    age = 30
    height = 1.75
    
    info = (
        f"Name: {name}\n"
        f"Age: {age}\n"
        f"Height: {height:.2f} meters"
    )
    print(info)
    # 输出:
    # Name: Alice
    # Age: 30
    # Height: 1.75 meters
    
    示例总结

    以下是 f-string 详细示例,展示了数字计算、字符串连接和函数执行等任务。

    name = "Alice"
    age = 30
    height = 1.75
    
    # 基本用法
    print(f"My name is {name} and I am {age} years old.")
    # 输出: My name is Alice and I am 30 years old.
    
    # 数字计算
    a = 5
    b = 3
    print(f"The sum of {a} and {b} is {a + b}.")
    # 输出: The sum of 5 and 3 is 8.
    
    print(f"{a} times {b} is {a * b}.")
    # 输出: 5 times 3 is 15.
    
    # 字符串连接
    first_name = "Alice"
    last_name = "Smith"
    print(f"My full name is {first_name + ' ' + last_name}.")
    # 输出: My full name is Alice Smith.
    
    # 函数执行
    def greet(name):
        return f"Hello, {name}!"
    
    print(f"Greeting: {greet(name)}")
    # 输出: Greeting: Hello, Alice!
    
    # 格式化选项
    value = 123.45678
    print(f"The value is {value:.2f}.")
    # 输出: The value is 123.46.
    
    num = 42
    print(f"Number: {num:04d}")
    # 输出: Number: 0042
    
    value = 3.14159
    print(f"Pi: {value:<10.2f}")
    # 输出: Pi: 3.14      
    
    # 嵌套表达式
    names = ["Alice", "Bob", "Charlie"]
    print(f"First name: {names[0]}")
    # 输出: First name: Alice
    
    print(f"Upper case name: {names[1].upper()}")
    # 输出: Upper case name: BOB
    
    # 多行 f-string
    info = (
        f"Name: {name}\n"
        f"Age: {age}\n"
        f"Height: {height:.2f} meters"
    )
    print(info)
    # 输出:
    # Name: Alice
    # Age: 30
    # Height: 1.75 meters
    

    4. 模板字符串

    模板字符串是通过 string 模块中的 Template 类实现的,使用 $ 作为占位符。

    用法
  • $name:变量占位符
  • $:转义符
  • 示例
    from string import Template
    
    name = "Alice"
    age = 30
    height = 1.75
    
    template = Template("My name is $name.")
    print(template.substitute(name=name))
    # 输出: My name is Alice.
    
    template = Template("I am $age years old.")
    print(template.substitute(age=age))
    # 输出: I am 30 years old.
    
    template = Template("My height is $height meters.")
    print(template.substitute(height=height))
    # 输出: My height is 1.75 meters.
    

    各种格式化方法对比与选择

    1. 百分号(%)格式化

    2. 优点:简单直观,适合简单的格式化需求。
    3. 缺点:功能有限,语法较老旧。
    4. 适用场景:老代码、需要兼容性高的项目。
    5. str.format() 方法

    6. 优点:功能强大,支持位置参数和关键字参数。
    7. 缺点:语法相对繁琐。
    8. 适用场景:需要复杂格式化的情况。
    9. f-string

    10. 优点:最现代、最简洁,支持嵌入变量、表达式和函数调用。
    11. 缺点:只适用于 Python 3.6 及以上版本。
    12. 适用场景:Python 3.6 及以上版本,任何需要格式化字符串的情况。
    13. 模板字符串

    14. 优点:简单易用,适合与非程序员协作。
    15. 缺点:功能相对简单,不支持复杂表达式。
    16. 适用场景:配置文件、模板文件等。

    示例总结

    # 百分号格式化
    print("Hello, %s! You have %d new messages." % ("Alice", 5))
    
    # str.format() 方法
    print("Hello, {}! You have {} new messages.".format("Alice", 5))
    
    # f-string
    name = "Alice"
    messages = 5
    print(f"Hello, {name}! You have {messages} new messages.")
    
    # 模板字符串
    from string import Template
    template = Template("Hello, $name! You have $messages new messages.")
    print(template.substitute(name="Alice", messages=5))
    

    根据具体需求和项目环境选择合适的格式化方法,以确保代码的可读性和维护性。

    作者:pumpkin84514

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python中的格式化输出详解

    发表回复