【Python】格式化输出引用变量类型:如:%s %d等
print("打印字符串:%s" %"string") print("打印整数:%d" % 2.365) print("打印浮点数(默认小数保留6位):%f" % 3.14159265358) print("打印浮点数(保留两位小数):%.2f" % 3.14159265358) print("打印浮点数(保留十位小数):%.10f" % 3.14159265358) print("科学计数法 %.2e" % 3.14159265358) print("占位符右对齐: %8s" % "aged") print("右对齐:Name:%10s Age:%8d Height:%8.2f" % ("Aviad", 25, 1.834)) print("占位符左对齐: %-8.2f" % 3.14159265358) print("左对齐:Name:%-10s Age:%-8d Height:%-8.2f" % ("Aviad", 25, 1.834))
执行结果:
format 格式化函数
- 格式化字符串的函数 str.format() 基本语法是通过 {} 和 : 来代替以前的 %
# 不限个参数,位置可以不按顺序 def position(): # 不设置指定位置 print("{} {}".format("九月你好","十月快来")) # 设置指定位置 print("{0} {2} {1}".format("九月你好","九月再见","十月快来")) # 设置参数 def para(): # 参数位置 print("{a},{b},{c}".format(a="今天星期四",b = "明天星期五",c = "后天休息日")) # 字段设置参数 site = {"name":"今天","year":"2021","mon":"09","day":"02"} print("{name}是特殊的日子{day},记录年月:{year}-{mon}".format(**site)) # 列表索引 list = ["02","09","2021"] print("{0[2]}-{0[1]}-{0[0]} 晴".format(list)) #取值格式0[索引号],0是固定值 if __name__ == "__main__": # position() para()
- 数字格式化
# 数字格式化 def numfun(): # num = print("保留2位小数", "{:.2f}".format(3.141592657)) print("保留符号并保留0位小数", "{:+.0f}".format(3.141592657)) print("整数左边补2×", "{:x>2d}".format(3)) print("整数右边补4×", "{:x<4d}".format(3)) print("逗号千位分隔", "{:,}".format(30000000)) print("百分比", "{:.2%}".format(0.1328)) if __name__ == "__main__": numfun()
-------------------------------------------------------------------------------------
如果万事开头难 那请结局一定圆满 @ Phoenixy
-------------------------------------------------------------------------------------