基本用法
1 2 3
| name = "Alice" age = 25 print("My name is {} and I'm {} years old.".format(name, age))
|
在这个例子中,大括号 {} 作为占位符,format() 方法中的参数按照顺序填充到占位符的位置。
指定参数顺序
1 2 3
| name = "Alice" age = 25 print("My name is {1} and I'm {0} years old.".format(age, name))
|
通过在占位符中使用索引号,可以指定参数的顺序。在这个例子中,{1} 表示第二个参数 name,{0} 表示第一个参数 age。
指定参数名
1 2 3
| name = "Alice" age = 25 print("My name is {n} and I'm {a} years old.".format(n=name, a=age))
|
格式设置
1 2
| value = 3.14159 print("The value is {:.2f}".format(value))
|
使用 : 可以进行进一步的格式设置。在这个例子中,:.2f 表示保留两位小数的浮点数格式。
对齐和填充
1 2 3 4 5
| text = "Hello" print("Left aligned: {:<10}".format(text)) print("Right aligned: {:>10}".format(text)) print("Center aligned: {:^10}".format(text)) print("Filled: {:_^10}".format(text))
|
通过使用 <、> 和 ^ 可以对文本进行左对齐、右对齐和居中对齐。在这个例子中,{:<10} 表示左对齐,占位符长度为 10;{:>10} 表示右对齐;{:^10} 表示居中对齐;{:_^10} 表示在文本两侧填充下划线,使其长度为 10。