format() 格式化函数

格式化字符串的函数 str.format(),增强了字符串格式化的功能

通过 {} 和 :来代替以前的 %

format() 函数可以接收不限个参数,位置可以不按顺序

实例:

# 作为拼接字符串进行使用
'{1} {1} {0} {0}'.format("hello", "world")	# 'world world hello hello'

# 保留小数
'{:.2f}'.format(3.1415926)  # 3,14

# 百分比格式
'{:.1f}'.format(0.25)  # 25.0%

# 进制转换
'{:b}'.format(12)  # '1100'     二进制
'{:d}'.format(12)  # '12'	十进制
'{:o}'.format(12)  # '14'	八进制
'{:x}'.format(12)  # 'c'	十六进制
原文地址:https://www.cnblogs.com/alivinfer/p/13282657.html