Python中使用.format方法替代格式化操作符%

Python中格式化字符串的方式有:


    格式化操作符%,基本语法:%[转换标记][宽度[.精确度]]转换类型,其中转换标记和转换类型详见《Python基础教程第2版》3.3节,《改善Python程序的91个建议》建议28;

    .format方法,基本语法:[[填充符]对齐方式][符号][#][0][宽度][,][.精确度][转换类型],其中填充符是除了“{}”外任意符号,对齐方式,符号,转换类型详见《91个建议》。


%常见用法:


    1.直接格式化字符或数值;

    >>>print "your score is %06.1f" % 9.5
    2.用元组格式化;

    >>>print "the %s of a circle with radius %f is %0.3f"  % (itemname,radius,math.pi*radius*2)
    3.用字典格式化;

    >>>itemdict = {'itemname':'circumference','radius':'3','value':math.pi*radius*2}

    >>>print "the %(itemname)s of a circle with radius %(radius)f is %(value)0.3f" % itemdict


.format常见用法:


    1.使用符号;

    >>>"The number {0:,} in hex is: {0:#x},the number {1} in oct is {1:#o}".format(4746,45)
    2.使用名称;

    >>>print "the max number is {max},the min number is {min},the average number is {average:0.3f}".format(max=189,min=12.6,average=23.5)
    3.通过属性

    >>>class Customer(object):

    ... def __init__(self,name,gender,phone):

    ... self.name = name

    ... self.gender = gender

    ... self.phone = phone

    ... def __str__(self):

    ... return 'Customer({self.name},{self.gender},{self.phone})'.format(self.self) #通过str函数返回结果

    4.格式化元组的具体项;

    >>>point = (1,3)

    >>>'X:{0[0]};Y:{0[1]}'.format(point)

参考书籍:

1.《Python基础教程第2版》

2.《编写高质量代码改善Python程序的91个建议》

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值