Python教程

Python format() 强化

本文主要是介绍Python format() 强化,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

format() 基础。

一、问题

通过format()函数和字符串方法使对象能支持自定义的格式化。


二、解决方案

为了自定义字符串的格式化,需要在类上面定义__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 == '':      # 如果为空,默认'ymd'
            code = 'ymd'
        fmt = _formats[code]
        print('fmt:',fmt)
        return fmt.format(d=self)

d = Date(2021, 12, 20)
print(format(d))
print(format(d, 'mdy'))

输出:

fmt: {d.year}-{d.month}-{d.day}
2021-12-20
fmt: {d.month}/{d.day}/{d.year}
12/20/2021

三、讨论

__format__()方法给 Python 的字符串格式化功能提供了一个钩子。这里需要强调的是格式化代码的解析工作由类自己决定。因此,格式化代码可以是任何值。

from datetime import date

d = date(2021, 12, 20)
print(format(d))
print(format(d, '%A, %B, %d, %Y'))
print('The end is {:%d %b %Y}. Goodbye'.format(d))

输出:

2021-12-20
Monday, December, 20, 2021
The end is 20 Dec 2021. Goodbye


这篇关于Python format() 强化的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!