您的位置:首页 > 编程语言 > Python开发

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

2016-10-15 15:51 796 查看
Python中格式化字符串的方式有:

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

    .format方法,基本语法:[[填充符]对齐方式][符号][#][0][宽度][,][.精确度][转换类型],其中填充符是除了“{}”外任
4000
意符号,对齐方式,符号,转换类型详见《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个建议》
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息