【问题标题】:Creating new conversion specifier in Python在 Python 中创建新的转换说明符
【发布时间】:2016-11-29 08:01:42
【问题描述】:

在 python 中,我们有转换说明符,例如

'{0!s}'.format(10)

哪个打印

'10'

我怎样才能使自己的转换说明符像

'{0!d}'.format(4561321)

以下列格式打印整数

4,561,321

或将其转换为二进制

'{0!b}'.format(2)

打印

10

我需要继承哪些类,需要修改哪些功能?如果可能,请提供一个小例子。

谢谢!!

【问题讨论】:

  • 我认为这不可能。但是,您可以这样做:'{0!b}'.format(MyInt(2)) 并通过实现 __format__ 特殊方法来获得它。
  • @Bakuriu MyInt() 会是什么?

标签: python python-2.7 python-3.x conversion-specifier


【解决方案1】:

你想做的事情是不可能的,因为内置类型不能修改,文字总是引用内置类型。

有一种特殊的方法来处理值的格式,即__format__,但是它只处理格式字符串,而不是转换说明符,即您可以自定义如何处理{0:d},但不能自定义如何处理{0!d}是。与! 一起工作的唯一东西是sr

注意db 已经作为格式说明符存在:

>>> '{0:b}'.format(2)
'10'

在任何情况下,您都可以实现自己的处理格式的类:

class MyInt:
    def __init__(self, value):
        self.value = value
    def __format__(self, fmt):
        if fmt == 'd':
            text = list(str(self.value))
        elif fmt == 'b':
            text = list(bin(self.value)[2:])
        for i in range(len(text)-3, 0, -3):
            text.insert(i, ',')
        return ''.join(text)

用作:

>>> '{0:d}'.format(MyInt(5000000))
5,000,000
>>> '{0:b}'.format(MyInt(8))
1,000

【讨论】:

    【解决方案2】:

    尽量不要自己做,尽量使用python中已经存在的默认函数。你可以使用,

    '{0:b}'.format(2)  # for binary
    '{0:d}'.format(2)  # for integer
    '{0:x}'.format(2)  # for hexadecimal
    '{0:f}'.format(2)  # for float
    '{0:e}'.format(2)  # for exponential
    

    更多信息请参考https://docs.python.org/2/library/string.html#formatspec

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 2019-09-28
      • 2013-12-20
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多