首页 > 其他 > 详细

格式化输入 \_\_format\_\_

时间:2020-02-02 15:36:20      阅读:96      评论:0      收藏:0      [点我收藏+]

格式化输入 __format__

格式化输入

一、__format__

  • 自定制格式化字符串
date_dic = {
    'ymd': '{0.year}:{0.month}:{0.day}',
    'dmy': '{0.day}/{0.month}/{0.year}',
    'mdy': '{0.month}-{0.day}-{0.year}',
}


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

    def __format__(self, format_spec):
        # 默认打印ymd的{0.year}:{0.month}:{0.day}格式
        if not format_spec or format_spec not in date_dic:
            format_spec = 'ymd'
        fmt = date_dic[format_spec]
        return fmt.format(self)


d1 = Date(2019, 12, 29)
print(format(d1))

print('{:mdy}'.format(d1))

2019:12:29

12-29-2019

格式化输入 \_\_format\_\_

原文:https://www.cnblogs.com/randysun/p/12252318.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!