码迷,mamicode.com
首页 > 其他好文 > 详细

2019年9月1日 定制format

时间:2019-09-01 16:32:30      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:2-2   字典   elf   for   def   nbsp   执行   not   span   

x=‘{0}{0}{0}‘.format(‘a‘)
print(x)

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


d1=Date(2099,1,2)
y=‘{0.year}{0.mon}{0.day}‘.format(d1)
z=‘{0.year}-{0.mon}-{0.day}‘.format(d1)
print(y)
print(z)

>>>>

aaa
209912
2099-1-2

 

format_dic={
    ‘ymd‘:"{0.year}:{0.mon}:{0.day}",
    ‘m-d-y‘:‘{0.mon}-{0.day}-{0.year}‘,
}

class Date:
    def __init__(self,year,mon,day):
        self.year=year
        self.mon=mon
        self.day=day
    def __format__(self, format_spec):
        print(‘format 执行‘)
        if not format_spec or format_spec not in format_spec: #如果 format_spec为空,或者不在字典的格式内
            format_spec=‘ymd‘
        fm=format_dic[format_spec]#通过字典来进行选择
        return fm.format(self)


d1=Date(2099,1,2)
zz=format(d1,‘ymd‘)
ww=format(d1,‘m-d-y‘)
print(zz)
print(ww)

》》》》

format 执行
format 执行
2099:1:2
1-2-2099

2019年9月1日 定制format

标签:2-2   字典   elf   for   def   nbsp   执行   not   span   

原文地址:https://www.cnblogs.com/python1988/p/11442406.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!