Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
print('{} {}'.format('hello','world')) # 不设置指定位置 print('{0} {1}'.format('hello','world')) #设置指定位置 print('{1} {0} {1}'.format('hello','world'))
输出结果:
hello world
hello world
world hello world
也可以设置参数:
#也可以指定参数 print('姓名:{name},地址:{address}'.format(name='cd',address='beijing')) #可以通过字典设置参数 info={'name':'cd','address':'yuyao'} print('姓名:{name},地址{address}'.format(**info)) #通过列表索引设置参数 lis=['cd','yuyao'] print('name:{0[0]},address:{0[1]}'.format(lis))#0是必须的
输出结果为
姓名:cd,地址:beijing
姓名:cd,地址yuyao
name:cd,address:yuyao
数字格式化
print('{:.2f}'.format(3.1415926535))#保留小数点后两位,输出3.14 print('{:+.2f}'.format(3.1415926535))#带符号保留小数点后两位,输出+3.14 print('{:+.2f}'.format(-1))#带符号保留小数点后两位,输出-1.00 print('{:.0f}'.format(2.71828))#四舍五入不带小数,输出3 print('{:0>2d}'.format(5))#数字补零(填充左边,宽度为2),输出05 print('{:x<4d}'.format(5))#数字补x(填充右边,宽度为4),输出5xxx print('{:x<4d}'.format(10))#数字补x(填充右边,宽度为4),输出10xx print('{:,}'.format(10000000))#以逗号分隔的数字形式,输出10,000,000 print('{:.2%}'.format(0.25))#百分比形式,输出25.00% print('{:.2e}'.format(1000000000))#指数形式,输出1.00e+09 print('{:10d}'.format(13))#右对齐,宽度为10,输出 13 print('{:<10d}'.format(13))#左对齐,宽度为10,输出13 print('{:^10d}'.format(13))#中间对齐,宽度为10,输出 13
若想输出大括号
print('{{}}'.format(0))#用{}来转义大括号