Can bin() be overloaded like oct() and hex() in Python 2.6?

后端 未结 4 548
旧时难觅i
旧时难觅i 2021-02-05 12:26

In Python 2.6 (and earlier) the hex() and oct() built-in functions can be overloaded in a class by defining __hex__ and __oct__

4条回答
  •  眼角桃花
    2021-02-05 13:27

    As you've already discovered, you can't override bin(), but it doesn't sound like you need to do that. You just want a 0-padded binary value. Unfortunately in python 2.5 and previous, you couldn't use "%b" to indicate binary, so you can't use the "%" string formatting operator to achieve the result you want.

    Luckily python 2.6 does offer what you want, in the form of the new str.format() method. I believe that this particular bit of line-noise is what you're looking for:

    >>> '{0:010b}'.format(19)
    '0000010011'
    

    The syntax for this mini-language is under "format specification mini-language" in the docs. To save you some time, I'll explain the string that I'm using:

    1. parameter zero (i.e. 19) should be formatted, using
    2. a magic "0" to indicate that I want 0-padded, right-aligned number, with
    3. 10 digits of precision, in
    4. binary format.

    You can use this syntax to achieve a variety of creative versions of alignment and padding.

提交回复
热议问题