目录
1.format()
1.1 作用
- 将一个字符串中的占位符(花括号
{}
)替换为指定的值或表达式。- 可以控制输出的格式,如数字的小数位数、日期的格式化等。
1.2 用法
- 基本语法:
"{ }".format(value)
- 在字符串中使用花括号
{}
指定占位符,然后调用format()
方法来传入实际的值或表达式。1.3 例子
# 基本用法 name = "Alice" age = 30 message = "Hello, my name is {} and I am {} years old.".format(name, age) print(message) # Output: Hello, my name is Alice and I am 30 years old. # 指定位置顺序 message = "The {1} jumped over the {0}.".format("moon", "cow") print(message) # Output: The cow jumped over the moon. # 格式化数字 pi = 3.14159265359 formatted_pi =
07-05
219
03-16
214
03-14
664