格式字符串

f-strings 的语法更加简洁明了,并且性能更好。

pi = 3.1415926
num = 10

# 格式化小数点后两位
formatted_pi = f"The value of pi is {pi:.2f}"
print(formatted_pi)

# 指定宽度为10,右对齐
formatted_num = f"Number: {num:10}"  
print(formatted_num)

# 指定宽度为10,左对齐
formatted_num = f"Number: {num:<10}"  
print(formatted_num)

name = "Alice"
age = 30

# 使用位置参数
message = "My name is {}, and I am {} years old.".format(name, age)
print(message)

# 使用关键字参数
message = "My name is {name}, and I am {age} years old.".format(name=name, age=age)
print(message)

# 格式化数字
pi = 3.1415926
formatted_pi = "The value of pi is {:.2f}".format(pi)
print(formatted_pi)

# 使用索引
values = (1, 2, 3)
message = "The values are {0}, {1}, and {2}".format(values[0], values[1], values[2])
print(message)