[Python-ideas] bytes indexing behavior

Franklin? Lee leewangzhong+python at gmail.com
Sat Jul 9 16:17:37 EDT 2016


On Jul 8, 2016 12:26 PM, "Michael Selik" <michael.selik at gmail.com> wrote:
>
> On Fri, Jul 8, 2016, 1:03 AM Franklin? Lee <leewangzhong+python at gmail.com>
wrote:
>>
>> On Jul 6, 2016 2:40 PM, "Michael Selik" <michael.selik at gmail.com> wrote:
>> > Instead it seems the best way given the current behavior is to write:
>> >
>> >     len(bytestring) == bytestring.count(b'z')
>> >
>> > While I wait for PEP 467, can anyone suggest a better way to write
that?
>>
>> How about
>>     set(bytestring) == set(b'z')
>
> Ah, that makes sense. I'd thought of using a set literal on the
right-hand, but for some reason using set constructor slipped my mind.

The previous method didn't allow short-circuiting. We can use `all` without
calling `ord` each time, by the obvious way.
        z = b'z'[0] #or next(iter(b'z'))
        all(byte == z for byte in bytestring)

Make it a function.
        def eqall(iterable, value):
            return all(x == value for x in iterable)

        eqall(bytestring, b'z'[0])

Rewriting in functional programming style.
        def eqall(iterable, value):
            return all(map(value.__eq__, iterable))
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160709/d5ff8dd8/attachment.html>


More information about the Python-ideas mailing list