[Python-ideas] bytes indexing behavior

Pavol Lisy pavol.lisy at gmail.com
Sun Jul 10 02:29:53 EDT 2016


On 7/9/16, Franklin? Lee <leewangzhong+python at gmail.com> wrote:
> 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))
>

Or if you want to accept more values:

def inall(iterable, values):
  return all(x in values for x in iterable)

inall(bytestring, list(b'zZ'))

PS. If you got this mail twice pls sorry - something goes wrong in my
mail client.


More information about the Python-ideas mailing list