format()方法是Python中用于格式化字符串的方法。它允许你将变量的值插入到字符串中的特定位置或者替换特定的占位符。
format
方法的基本语法如下:
string.format(value1, value2, ...)
其中:
string
是包含占位符{}
的字符串,这些占位符将被实际的值替换。value1
,value2
, … 是要插入到字符串中的值。
示例:
name = "Alice"
age = 30
# 使用format方法将变量的值插入到字符串中
message = "My name is {}. I am {} years old.".format(name, age)
print(message)
输出:
My name is Alice. I am 30 years old.
在上面的示例中,format
方法将 name
和 age
的值插入到了字符串中的占位符中。
你还可以在占位符中指定格式,例如:
pi = 3.141592653589793
# 使用format方法将变量的值插入到字符串中,并限制小数位数
formatted_pi = "The value of pi is approximately {:.2f}".format(pi)
print(formatted_pi)
输出:
The value of pi is approximately 3.14
在这个示例中,{:.2f}
表示将 pi
的值格式化为保留两位小数的浮点数。
format
方法还支持许多其他的格式选项,包括对整数、日期、百分比等的格式化。它提供了非常灵活的方式来控制字符串的输出格式。