'''format字符串格式化''' m = '{0}{0}{0}'.format('ok') print(m) class Date: def __init__(self, year, mon, day): self.year = year self.mon = mon self.day = day d1 = Date(2021, 4, 29) n = '{}{}{}'.format(d1.year, d1.mon, d1.day) n1 = '{0}{0}{0}'.format(d1) # <__main__.Date object at 0x0000021F8C078490> <__main__.Date object at 0x0000021F8C078490> <__main__.Date object at 0x0000021F8C078490> n2 = '{0.year}{0.mon}{0.day}'.format(d1) print(n) print(n1) print(n2) '''自定制format''' # 先定制一个格式字典 format_dic = { 'ymd': '{0.year}/{0.mon}/{0.day}', 'm-y-d': '{0.mon}-{0.year}-{0.day}', 'y:m:d': '{0.year}:{0.mon}:{0.day}' } class Date_one: def __init__(self, year, mon, day): self.year = year self.mon = mon self.day = day def __format__(self, format_spec): # 参数为定制格式字典的key if not format_spec or format_spec not in format_dic: # 判断format_spec参数为空和不等于format_dic的key值的情况 format_spec = 'ymd' fm = format_dic[format_spec] # 取到key对应的value,即格式本身 return fm.format(self) # __format__必须要有返回值,且返回值必须为字符串类型 d2 = Date_one(2021, 4, 30) print(format(d2)) print(format(d2, 'm-y-d')) print(format(d2, 'y:m:d'))