Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-builtin-functions-format.html

python 用于将字符串格式化的内置函数 format 详解

Python 内置函数 Python 内置函数


str.format() 是 Python 中用于字符串格式化的内置方法。它允许你将变量的值插入到字符串中的特定位置,创建更加灵活和可读性高的输出。

函数语法

formatted_string = "template string".format(arguments)

参数: 

  • formatted_string :生成的格式化后的字符串。
  • "template string" :包含占位符 {} 的字符串模板,用于定义最终格式化后的字符串的结构。
  • arguments :是一个或多个要插入到模板中的值。

在模板字符串中,你可以使用大括号 {} 来表示一个占位符,然后在 format() 方法中提供实际的值来填充这些占位符。

示例代码

示例 1:基本用法

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

运行结果:

My name is Alice and I am 30 years old.

示例 2:位置参数

formatted_string = "My favorite fruits are {} and {}.".format("apple", "banana")
print(formatted_string)

运行结果:

My favorite fruits are apple and banana.

示例 3:关键字参数

formatted_string = "My favorite colors are {color1} and {color2}.".format(color1="blue", color2="green")
print(formatted_string)

运行结果:

My favorite colors are blue and green.

示例 4:序号参数

formatted_string = "The first element is {0}, the second element is {1}, and the third element is {2}.".format(10, 20, 30)
print(formatted_string)

运行结果:

The first element is 10, the second element is 20, and the third element is 30.

示例 5:混合使用

name = "Bob"
age = 25
formatted_string = "My name is {name} and I am {age} years old. {name} likes {fruit}.".format(name=name, age=age, fruit="orange")
print(formatted_string)

运行结果:

My name is Bob and I am 25 years old. Bob likes orange.

总结

str.format() 方法是 Python 中用于字符串格式化的强大工具。通过在字符串模板中使用占位符 {},并在 format() 方法中提供相应的值,你可以创建具有可读性和灵活性的格式化字符串。你可以使用位置参数、关键字参数、序号参数等不同的方式来填充占位符。这使得生成复杂的输出变得更加容易,并且可以用于打印日志、生成报告、构建用户界面等各种应用场景。