Python_day10--format

一、format函数

format是python2.6新增的一个格式化字符串的方法,

相对于老版的%格式方法,它有很多优点。

        1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型

        2.单个参数可以多次输出,参数顺序可以不相同

        3.填充方式十分灵活,对齐方式十分强大

        4.官方推荐用的方式,%方式将会在后面的版本被淘汰

1、通过位置来填充字符串

print("hello {0}".format((1, 2, 3, 4)))
print("hello {0} {1} {0} {1}".format((1, 2, 3, 4), "python"))
print("hello {0:.3f}".format(1.8989))

2、通过key来填充

print("max:{max} min:{min}".format(min=10, max=100))

3、通过下标/index填充

a = (3,4)
print("x:{0[0]}, y:{0[1]}".format(a))

4、通过字典的key

d = {'max':100.123456789, 'min':10.123456789}
print("max:{max:.2f} min:{min:.3f}".format(**d))

5、oop对象进行操作

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

    # 打印对象时自动调用;str(对象)
    def __str__(self):
        return "书名:{0.name} 作者:{0.author} 位置:{0.bookIndex}".format(self)
        # return "书名:{d.name} 状态:{d.state}".format(d=self)

b = Book("java", '詹姆斯·高斯林', 1, '一楼东侧')
print(b)

6、填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度

print('{:^14}'.format('小星星'))
print('{:>14}'.format('小星星'))
print('{:*>14}'.format('小星星'))
print('{:<14}'.format('小星星'))
print('{:*<14}'.format('小星星'))


二、类中的__format__方法

例:格式化输出<年-月-日>或<日-月-年>字符串

setter = {
    'ymd':"{d.year}-{d.month}-{d.day}",
    'dmy':"{d.day}-{d.month}-{d.year}"
}

class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def __format__(self, format_spec):
        if not format_spec:
            format_spec = 'ymd'
        fmt = setter[format_spec]

        return fmt.format(d=self)


d = Date('2018', '5', '23')
print(format(d, 'ymd'))
print(format(d, 'dmy'))
print(format(d))








猜你喜欢

转载自blog.csdn.net/biu_biu_0329/article/details/80425097
今日推荐