• python 格式化字符串的方法


    在 Python 中,格式化字符串有多种方法,每种方法都有其独特的优点和适用场景。以下是几种常用的格式化字符串的方法:

    1.使用百分号 (%) 运算符

    这是 Python 中最早的字符串格式化方式,类似于 C 语言中的 printf

    1. name = "Alice"
    2. age = 30
    3. formatted_string = "My name is %s and I am %d years old." % (name, age)
    4. print(formatted_string)

    格式说明符

    • %s:字符串
    • %d:整数
    • %f:浮点数
    • %.2f:保留两位小数的浮点数

    2.使用 str.format() 方法

    这是 Python 2.7 和 3.0 引入的一个更强大的字符串格式化方法。

    1. name = "Alice"
    2. age = 30
    3. formatted_string = "My name is {} and I am {} years old.".format(name, age)
    4. print(formatted_string)

    带位置参数和关键字参数

    1. formatted_string = "My name is {0} and I am {1} years old.".format(name, age)
    2. print(formatted_string)
    3. formatted_string = "My name is {name} and I am {age} years old.".format(name="Alice", age=30)
    4. print(formatted_string)

    格式说明符

    • {}:默认位置
    • {0}:位置参数
    • {name}:关键字参数
    • {:.2f}:保留两位小数的浮点数

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

    这是 Python 3.6 引入的一种更简洁、更直观的方法。

    1. name = "Alice"
    2. age = 30
    3. formatted_string = f"My name is {name} and I am {age} years old."
    4. print(formatted_string)

    支持表达式

    1. formatted_string = f"Next year I will be {age + 1} years old."
    2. print(formatted_string)

    格式说明符

    • {value:.2f}:保留两位小数的浮点数

    4.使用 string.Template 类

    这是 Python 标准库中的一种替代方法,适用于需要更简单替换的情况。

    1. from string import Template
    2. name = "Alice"
    3. age = 30
    4. template = Template("My name is $name and I am $age years old.")
    5. formatted_string = template.substitute(name=name, age=age)
    6. print(formatted_string)

    在需要提供缺省值时使用 safe_substitute 方法:

    1. template = Template("My name is $name and I am $age years old.")
    2. formatted_string = template.safe_substitute(name="Alice")
    3. print(formatted_string)
    4. # 输出: My name is Alice and I am $age years old.

    总结

    不同的格式化字符串方法有不同的适用场景:

    • 百分号 (%) 运算符:适用于简单的格式化,通常用于老代码中。
    • str.format() 方法:更强大和灵活,适用于复杂的格式化需求。
    • f-strings:最简洁直观,适用于 Python 3.6 及以上版本,是推荐的格式化方法。
    • string.Template 类:适用于需要替换标记的简单模板,尤其是需要与非 Python 代码进行交互时。

    选择哪种方法取决于你的具体需求和代码风格。对于大多数情况,推荐使用 f-strings 由于其易读性和性能。

  • 相关阅读:
    将旧硬盘放入新主机当作资料盘时,忘记查看旧电脑IP怎么办?
    html5——前端笔记
    Hadoop 高可用配置及其集群搭建
    node日志log4js库使用示例
    linux 安装python django pip 遇到的问题
    使用fvm切换flutter版本
    【NAS】整机备份还原Windows/Linux系统,群晖最强套件ABB教程
    Bad format for Timestamp ‘203‘ in column 1
    《性能之巅第2版》阅读笔记(五)--file-system监测
    主机安全防护五大难点攻克
  • 原文地址:https://blog.csdn.net/mzl_18353516147/article/details/139837699