format函数
1、基础用法
print("{} {}!".format("hello", "world"))
print("{1} {0}!".format("hello", "world"))
print("{1} {0} {1}".format("hello", "world"))
hello world !
world hello !
world hello world
2、设置参数
print("名字:{name}, 性别: {sex}".format(name="Emma", sex="W"))
# 通过字典设置参数
student_1 = {"name": "Emma", "sex": "W"}
print("名字:{name}, 性别: {sex}".format(**student_1))
print("名字:{0[name]}, 性别: {0[sex]}".format(student_1))
# 通过列表索引设置参数
my_list = ['Emma','W']
print("名字:{0[0]}, 性别: {0[1]}".format(my_list))
名字:Emma, 性别: W
名字:Emma, 性别: W
名字:Emma, 性别: W
名字:Emma, 性别: W
3、数字格式化
# 保留两位小数
print("{:.2f}".format(3.1415926))
# 右填充
print("{: >6d}".format(3))
# 左填充
print("{:_<6d}".format(3))
# 居中填充
print("{:_^7d}".format(3))
# 科学计数法表示
print("{:,}".format(10000000))
# 百分比格式
print("{:.2%}".format(0.25))
3.14
3
3_____
___3___
10,000,000
25.00%
经典例题
键盘输入正整数 n,按要求把 n 输出到屏幕,格式要求:宽度为 25 个字符,等号字符 (=) 填充,右对齐,带千位分隔符。如果输入正整数超过 25 位,则按照真实长度输出。
s = input()
print("{:=>25,}".format(eval(s)))