format() 是 Python 字符串对象的一个方法,用于格式化字符串。它允许您插入变量或值到字符串中,并指定它们的格式。
formatted_string = "Some text with {} and {}".format(value1, value2)
在这个例子中,{} 是占位符,而 value1 和 value2 是将替换占位符的值。您可以在字符串中使用多个占位符,并通过传递相应数量的参数来替换它们。
# 基本用法
name = "Alice"
age = 25
info = "My name is {} and I am {} years old.".format(name, age)
print(info)
# Output: My name is Alice and I am 25 years old.
# 指定占位符的顺序
sentence = "{1} is a {0}.".format("fruit", "Banana")
print(sentence)
# Output: Banana is a fruit.
# 格式化数字
pi_value = 3.14159
formatted_pi = "The value of pi is {:.2f}".format(pi_value)
print(formatted_pi)
# Output: The value of pi is 3.14
在这个例子中,format() 方法通过传递的参数替换字符串中的占位符。占位符中的数字 {0}、{1} 等用于指定要使用的参数的顺序,而 :.2f 指定浮点数的格式,保留两位小数。format() 方法提供了丰富的格式化选项,可以根据需要进行调整。
博客介绍了Python字符串对象用于格式化字符串的方法。该方法允许插入变量或值到字符串中,可使用多个占位符,并通过传递相应参数替换。占位符中的数字指定参数顺序,还能指定浮点数等格式,有丰富格式化选项。
8万+

被折叠的 条评论
为什么被折叠?



