美文网首页
python 自定义字符串的输出格式

python 自定义字符串的输出格式

作者: 孙广宁 | 来源:发表于2022-05-26 23:00 被阅读0次
    8.2 我们想通过对象的format函数的字符串方法来支持自定义的格式输出
    • 可以再类中定义format()方法
    >>> _formats = { 'ymd':'{d.year}-{d.month}-{d.day}','mdy':'{d.month}/{d.day}/{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(2022,5,27)
    >>> format(d)
    '2022-5-27'
    >>> format(d,'mdy')
    '5/27/2022'
    >>> 'the date is :{:ymd}'.format(d)
    'the date is :2022-5-27'
    >>> 'the date is :{:mdy}'.format(d)
    'the date is :5/27/2022'
    >>>
    
    • 也可以用下述方法调用,可能理解上比较直接
    >>> d.__format__("ymd")
    '2022-5-27'
    >>> d.__format__("mdy")
    '5/27/2022'
    >>>
    

    相关文章

      网友评论

          本文标题:python 自定义字符串的输出格式

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