Python中查看一些框架代码,做日志输出或者做面试题中,经常需要了解到格式化输出的理解。
看下面的代码就了解了格式化输出的用法了:
# 直接使用
print("Name:%s Age:%d Height:%f" % ("Aviad",25,1.83))
# Name:Aviad Age:25 Height:1.830000
# 指定占位符宽度 +号右对齐 -左对齐 默认占位符时空格
print("Name:%10s Age:%8d Height:%8.2f" % ("Aviad", 25, 1.83))
# Name: Aviad Age: 25 Height: 1.83
# -左对齐
print("Name:%-10s Age:%-8d Height:%.2f" % ("Aviad", 25, 1.83))
# Name:Aviad Age:25 Height:1.83
# 用0作为占位符
print("Name:%-10s Age:%08d Height:%08.3f"%("Aviad",25,1.83))
# Name:Aviad Age:00000025 Height:0001.830