美文网首页
python 自定义格式化__format__

python 自定义格式化__format__

作者: SkTj | 来源:发表于2019-12-03 13:46 被阅读0次

为了自定义字符串的格式化,我们需要在类上面定义 format() 方法。例如:

_formats = {
'ymd' : '{d.year}-{d.month}-{d.day}',
'mdy' : '{d.month}/{d.day}/{d.year}',
'dmy' : '{d.day}/{d.month}/{d.year}'
}

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

def __format__(self, code):
    if code == '':
        code = 'ymd'
    fmt = _formats[code]
    return fmt.format(d=self)

现在 Date 类的实例可以支持格式化操作了,如同下面这样:

d = Date(2012, 12, 21)
format(d)
'2012-12-21'
format(d, 'mdy')
'12/21/2012'
'The date is {:ymd}'.format(d)
'The date is 2012-12-21'
'The date is {:mdy}'.format(d)
'The date is 12/21/2012'

相关文章

  • python 自定义格式化__format__

    为了自定义字符串的格式化,我们需要在类上面定义 format() 方法。例如: _formats = {'ymd'...

  • python基础知识(3)

    python字符串 python转义字符 python字符串运算符 python字符串格式化 python格式化操...

  • 超详细的Xcode代码格式化教程,可自定义样式

    超详细的Xcode代码格式化教程,可自定义样式 超详细的Xcode代码格式化教程,可自定义样式

  • 字符串的格式化操作

    旧式字符串格式化%运算符,位置格式化(python2) str.format字符串格式化(python3,它存在一...

  • python2,3的小秘密

    Python字符串格式化,有两个版本 1.Python2.5之前,我们使用的使用老式的格式化 2.Python3....

  • 实战

    python的格式化输出 #python格式化输出 ##%对于未知变量类型,用这样就不太方便了 name='lis...

  • 格式化Curl返回的Json字符

    格式化Curl返回的Json字符 格式化Curl返回的Json字符Python 格式化Nodejs 格式化 经常会...

  • Python学习笔记-3群18组-杜杜狼-2017.7.26

    在昨天的学习中发现自己对python的格式化还不明白,今天专门研究一下格式化。 Python格式化学习 Pytho...

  • 4.2 Python

    4.2.1. 格式化字符串   在Python中,有两种格式化字符串的方式,在Python2的较低版本中,格式化字...

  • 013.Python格式化

    Python格式化 1. 概述 Python2.6 开始,新增了一种格式化字符串的函数 str.format(),...

网友评论

      本文标题:python 自定义格式化__format__

      本文链接:https://www.haomeiwen.com/subject/upgfpctx.html