一.传统的%操作符

1.直接格式化字符

1
print "your score is %06.1f" % 9.5

2.以元组的形式格式化

1
2
3
country = 'China'
province = 'ShangXi'
print "I come from %s %s" %(country, province)

3.以字典的形式格式化

1
2
info = {'country':'China', 'province':'ShangXi'}
print 'I come from %(province)s, %(country)s' % info

二.format常见用法

1.使用位置符号

1
2
>>"The number {0:,} in hex is: {0: #x}, the number {1} in oct is {1:#o}".format(4746, 45)
'The number 4,746 in hex is: Ox128a, the number 45 in oct is 0o55'
在这里{0:,}金额的千位分隔符

2.使用名称

1
print 'The max is {max} the min is {min} the average is {avg:0.3f}'.format(max=13, min=2, avg=12.21)

3.通过属性

1
2
3
4
5
6
class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return 'Point({self.x}, {self.y})'.format(self=self)
1
2
>>str(Point(1, 2))
'Point(1, 2)

4.格式化元组的具体项

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

三.最后比较:

1.format方式比%操作符更为灵活,使用format方式时,参数的顺序与格式化的顺序不必完全相同 2.format可以方便地作为参数传递

1
2
3
4
weather= [('Monday', 'rain'), ('Tuesday', 'sunny'), ('Wednesday', 'sunny'), ('Thursday', 'rain'), ('Friday', 'cloudy')]
formatter = "Weather of {0[0]} is {0[1]}".format
for item in map(formatter, weather):
    print item
1
2
3
4
5
Weather of Monday is rain
Weather of Tuesday is sunny
Weather of Wednesday is sunny
Weather of Thursday is rain
Weather of Friday is cloudy

3.根据官方文档 .format()方法最终会取代%, 保留%为了向后兼容 4.%格式化元组时, 需要小心

1
2
info = ('tmac', '30')
print 'Info: %s' % (info)

会报错

1
2
print 'Info:{}'.format(info)

不会抛出异常

所以如果字符本身为元组, 则需要使用 (info, )这种形式才嫩避免错误

Final: 此篇为《Effective Python》读书笔记