Python的format函数可以用来格式化字符串。以下是使用format函数的示例:
name = "Alice"
age = 30
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
输出结果为:My name is Alice and I am 30 years old.
name = "Bob"
age = 25
message = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(message)
输出结果为:My name is Bob and I am 25 years old.
name = "Charlie"
age = 20
message = "My name is {0} and I am {1} years old.".format(name, age)
print(message)
输出结果为:My name is Charlie and I am 20 years old.
pi = 3.14159
formatted_pi = "Pi is approximately {:.2f}".format(pi)
print(formatted_pi)
输出结果为:Pi is approximately 3.14
以上是使用format函数的一些常见示例,你可以根据自己的需求来选择合适的方式来格式化字符串。