Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 。format 函数可以接受不限个参数,位置可以不按顺序。
1、格式化字符
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
"{0} {1}".format("hello", "world") # 设置指定位置
"{1} {0} {1}".format("hello", "world") # 设置指定位置
输出:
‘hello world’
‘hello world’
‘world hello world’
2、格式化数字
{:.2f} #保留小数点后两位
{:+.2f} #带符号保留小数点后两位
{:.0f} #不带小数
{:.2%} # 百分比格式
{:.2e} # 指数记法
{:b}.format(11) #二进制
{:d}.format(11) # 十进制
{:o}.format(11) # 八进制
{:x}.format(11) # 十六进制
{:#x}.format(11) # 以0x开头(小写)
{:#X}.format(11) # 以0x开头 (大写)
此外我们可以使用大括号 {} 来转义大括号,如下实例:
print ("{} 对应的位置是 {{0}}".format("runoob"))
输出:
runoob 对应的位置是 {0}
参考文章1:Python format 格式化函数