python-强大的format函数

format函数

是一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串
它通过{}来代替%
1.通过位置

print "{0} {1} {1} {0}".format(1,2,3,4)

这里写图片描述
2.通过关键字参数

print "{year} {month} {day}".format(month=10,day=20,year=1998)

这里写图片描述

class Book(object):
    def __init__(self, name, author, state, bookIndex):
        self.name = name
        self.author = author
        # 0: 借出  1: 未借出
        self.state = state
        self.bookIndex = bookIndex

    def __str__(self):
        if self.state == 1:
            stat = '未借出'
        elif self.state == 0:
            stat = "借出"
        else:
            stat = "异常"
        return "书名:《{d.name}》 作者:{d.author}   \
               状态: {stat}  位置: {d.bookIndex}".format(d=self, stat=stat)

d=Book('python','Guido',0,'Indx879')
print d

这里写图片描述
3.通过映射
list : 通过索引

a_list = ['LiMing','18','china']
print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list)  #{0[]} 0表示fotmat函数的参数位置

这里写图片描述
dict 通过key值,访问value

dict = {
    'name':'Liming',
    'age':'20',
    'home':'china'

}

print 'my name is {name},from {home},age is {age}'.format(**dict)

这里写图片描述
4.填充与对齐

print '{:>8}'.format('1020')
print '{:0>8}'.format('1020')
print '{:a>8}'.format('1020')

这里写图片描述
5.精度与类型

print '{:.2f}'.format(321.33345)   #保留两位小数

print '{:,}'.format(1234567890)  #用来做金额的千位分隔符

这里写图片描述


print '{:b}'.format(18)  #二进制

print '{:d}'.format(18) #十进制

print '{:o}'.format(18) #八进制

print '{:x}'.format(18) #十六进制

这里写图片描述

猜你喜欢

转载自blog.csdn.net/mashaokang1314/article/details/79982450