[Python-ideas] Add an option for delimiters in bytes.hex()

Nick Coghlan ncoghlan at gmail.com
Wed May 3 09:46:54 EDT 2017


On 3 May 2017 at 08:10, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> For a name, I think "group" would be better than "chunk".
> We talk about grouping the digits of a number, not chunking
> them.

As soon as I added an intermediate variable to my example, I came to
the same conclusion:

    >>> digit_groups = b'\xb9\x01\xef'.hex().splitgroups(2)
    >>> ' '.join(digit_groups)
    'b9 01 ef'

(from http://bugs.python.org/issue22385#msg292900)

And for David's telephone number examples:

    >>> digit_groups = str(4135559414).rsplitgroups(4,3)
    >>> '-'.join(digit_groups)
    '413-555-9414'

    >>> digit_groups = "0113225551212".rsplitgroups(2,2,3,1,2,3)
    >>> '-'.join(digit_groups)
    '011-32-2-555-12-12'

Another example would be generating numeric literals with underscores:

    >>> digit_groups = str(int(1e6).rsplitgroups(3)
    >>> '_'.join(digit_groups)
    '1_000_000'

While a generalised reversed version wouldn't be possible, a
corresponding "itertools.itergroups" function could be used to produce
groups of defined lengths as islice iterators, similar to the way
itertools.groupby works (i.e. producing subiterators of variable
length rather than a fixed length tuple the way the grouper() recipe
in the docs does).

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list