赞
踩
Python 提供了多种格式化输出的方法,常见的有以下几种:
str.format()
方法每种方法都有其独特的用法和适用场景。下面我们逐一详细讲解并举例说明。
这种方法类似于 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%
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.
f-string(格式化字符串字面量)是 Python 3.6 引入的一种格式化字符串的方法。f-string 使用 f
或 F
前缀,并在大括号 {}
中直接放入变量、表达式、函数调用等,可以动态生成字符串。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,使其更具可读性。
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
模板字符串是通过 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.
百分号(%)格式化:
str.format()
方法:
f-string:
模板字符串:
# 百分号格式化
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))
根据具体需求和项目环境选择合适的格式化方法,以确保代码的可读性和维护性。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。