format函数在Python中用于格式化字符串,其基本语法如下:
"{}".format(value)
{}是占位符,value是要插入的值。
print("我的名字是{},我{}岁了。".format("张三", 20))
输出结果为:
我的名字是张三,我20岁了。
format()方法还支持更复杂的格式化,例如:
- 数字格式化:
print('{:.2f}'.format(3.1415926)) # 输出结果为:3.14
- 字符串对齐:
print('{:<10}'.format('hello')) # 左对齐,输出结果为:hello print('{:>10}'.format('hello')) # 右对齐,输出结果为: hello print('{:^10}'.format('hello')) # 居中,输出结果为: hello
- 填充和制表符:
print('{:^10}'.format('hello')) # 使用空格填充,输出结果为: hello print('{:=^10}'.format('hello')) # 使用制表符填充,输出结果为:=hello=