1.f-string方法案例:
点击查看代码
# 计算圆的面积
import math
def calculate_circle_area(radius):
"""计算圆的面积"""
return math.pi * (radius ** 2)
radius = 5 # 圆的半径
area = calculate_circle_area(radius)
print(f"圆的面积为: {area:.2f}")
点击查看代码
name = "Ki"
age = 30
print("Hello, %s. You are %d years old." % (name, age))
点击查看代码
name = "Ki"
age = 30
print("Hello, {}. You are {} years old.".format(name, age))
点击查看代码
fmt = "Hello, {name}. You are {age} years old."
data = {'name': 'Ki', 'age': 30}
print(fmt.format_map(data))
5.% 操作符与元组:
点击查看代码
args = ("Ki", 30)
print("Hello, %s. You are %d years old." % args)
6.字符串拼接:
虽然不是真正的格式化方法,但简单地通过 + 操作符拼接字符串也是一种常见的做法:
点击查看代码
name = "Ki"
age = 30
print("Hello, " + name + ". You are " + str(age) + " years old.")
7.使用 join() 方法:
如果你有多个字符串片段和一个分隔符,可以使用 join() 方法:
点击查看代码
name = "Ki"
age = 30
parts = ["Hello, ", name, ". You are ", str(age), " years old."]
print("".join(parts))
8.模板字符串(Template Strings):
Python 的 string 模块提供了 Template 类,它允许你使用 $ 符号嵌入变量:
点击查看代码
from string import Template
t = Template("Hello, $name. You are $age years old.")
print(t.substitute(name="Ki", age=30))