美文网首页
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(一)字符串操作

    Python字符串的操作 一: python字符串的格式 双引号或者单引号中的数据都是字符串 二: 字符串的输出 ...

  • python—输入与输出

    Python的格式化输出 使用字符串格式化的形式来优化Python的输出,使用%作为占位符。%后面跟的是变量的类型...

  • 字符串操作

    Python字符串 字符串格式化 Python将若干值插入到带有"%"标记的字符串中,从而可以动态的输出字符串 ...

  • 与C/C++的不同

    #格式化输出字符串 在C中输出字符串语法是 'printf("age is %d",age);' 而在Python...

  • python3:字符串的格式化输出

    字符串的格式化输出由槽格式和format()来组成的.举个例子: 该python为python3.x版...

  • Python学习基础知识之 字符串String 的方法以及基本使

    目录 一、Python字符串的介绍 1.1python中的字符串格式: 1.2字符串的输出案例 1.3字符串输入案...

  • 3/20python之格式化字符串

    格式化字符串,就是将字符串以特定格式输出。 Python2.6 开始,新增了一种格式化字符串的函数 【str.fo...

  • 【python】格式化输出

    python print格式化输出。 打印字符串print ("His name is %s"%("ofish")...

  • 2018-07-06

    python格式化输出%与format方法对比 本来已经学完字符串的format格式,今天看到还有...

  • Python习题册001:格式化输出

    任务001描述: 编写一个Python程序,以特定的格式输出。示例字符串及输出效果如下:示例字符串: "Twink...

网友评论

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

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