【387】Python format 格式化函数(以及 %)
参考:python基础_格式化输出(%用法和format用法)
# 保留小数点后两位 f'{3.1415926:.2f}' # 带符号保留小数点后两位 f'{3.1415926:+.2f}' f'{-1:+.2f}' # 不带小数 f'{2.71828:.0f}' # 数字补零 (填充左边, 宽度为2) f'{5:02}' f'{5:02d}' f'{5:0>2}' f'{5:0>2d}' # 数字补x (填充右边, 宽度为4) f'{5:x<4}' f'{5:x<4d}' # 以逗号分隔的数字格式 f'{1000000:,}' # 百分比格式 f'{0.25:%}' f'{0.25:.2%}' # 指数记法 f'{10000000:e}' f'{10000000:.2e}' # 右对齐 (默认, 宽度为10) f'{13:>10}' f'{13:>10d}' # 左对齐 (宽度为10) f'{13:<10}' f'{13:<10d}' # 中间对齐 (宽度为10) f'{13:^10}' f'{13:^10d}' output: '3.14' '+3.14' '-1.00' '3' '05' '05' '05' '05' '5xxx' '5xxx' '1,000,000' '25.000000%' '25.00%' '1.000000e+07' '1.00e+07' ' 13' ' 13' '13 ' '13 ' ' 13 ' ' 13 '
上面主要是数字的输出,如果是一些变量的输出,可以按照下面的方法
- format:可以里面定义不同的数字,然后重复利用添加的信息
-
格式为:
-
"...{0}...{1}".format(var0, var1)
-
- %:可以设置不同的数据类型
-
格式为:
-
"...%s...%d..."%(var1, var2)
-
-
format 需要有个 dot,是一个方法,后面是个括号,需要填入的信息都在里面,用逗号分开
-
% 直接跟在后面,之后跟着一个括号,需要填入的信息都在里面,用逗号分开
>>> name = "Alex" >>> age = 18 >>> print("I am {0} and I am {1} years old.".format(name, age)) I am Alex and I am 18 years old. >>> print("I am {} and I am {} years old.".format(name, age)) I am Alex and I am 18 years old. >>> print("I am %s and I am %d years old."%(name, age)) I am Alex and I am 18 years old. >>> print("I am %s and I am %d years old. Just call me %s."%(name, age, name)) I am Alex and I am 18 years old. Just call me Alex. # 添加数字的原因是可以重复利用默写内容 >>> print("I am {0} and I am {1} years old. Just call me {0}.".format(name, age)) I am Alex and I am 18 years old. Just call me Alex. >>> pi = 3.1415926 >>> print("The value of PI is {}.".format(f'{3.1415926:.2f}')) The value of PI is 3.14.