[issue22385] Define a binary output formatting mini-language for *.hex()

Nick Coghlan report at bugs.python.org
Mon May 1 22:10:58 EDT 2017


Nick Coghlan added the comment:

Minimalist proposal:

    def hex(self, *, bytes_per_group=None, delimiter=" "):
        """B.hex() -> string of hex digits
        B.hex(bytes_per_group=N) -> hex digits in groups separated by *delimeter*
    
        Create a string of hexadecimal numbers from a bytes object::

        >>> b'\xb9\x01\xef'.hex()
        'b901ef'
        >>> b'\xb9\x01\xef'.hex(bytes_per_group=1)
        'b9 01 ef'
        """

Alternatively, the grouping could be by digit rather than by byte:

    def hex(self, *, group_digits=None, delimiter=" "):
        """B.hex() -> string of hex digits
        B.hex(group_digits=N) -> hex digits in groups separated by *delimeter*
    
        Create a string of hexadecimal numbers from a bytes object::

        >>> b'\xb9\x01\xef'.hex()
        'b901ef'
        >>> b'\xb9\x01\xef'.hex(group_digits=2)
        'b9 01 ef'
        """

One potential advantage of the `group_digits` approach is that it could be fairly readily adapted to the hex/oct/bin builtins (although if we did that, it would make the lack of a "dec" builtin for decimal formatting a bit weird)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue22385>
_______________________________________


More information about the Python-bugs-list mailing list