Python 3.x and bytes

Ethan Furman ethan at stoneleaf.us
Tue May 17 16:55:36 EDT 2011


Corey Richardson wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> On 05/17/2011 02:47 PM, Ethan Furman wrote:
>> In Python 3 one can say
>>
>> --> huh = bytes(5)
>>
>> Since the bytes type is actually a list of integers, I would have 
>> expected this to have huh being a bytestring with one element -- the 
>> integer 5.  Actually, what you get is:
>>
>> --> huh
>> b'\x00\x00\x00\x00\x00'
>>
>> or five null bytes.  Note that this is an immutable type, so you cannot 
>> go in later and say
> 
> For the bytes to actually be a 'list of integers', you need to pass it
> an iterable, ex:
>>>> bytes([5, 6, 1, 3])
> b'\x05\x06\x01\x03'

Not so.

--> huh = b'abcedfg'
--> huh[3]
101

It's a list of int's.

> - From help(bytes):
>  |  bytes(iterable_of_ints) -> bytes
>  |  bytes(string, encoding[, errors]) -> bytes
>  |  bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
>  |  bytes(memory_view) -> bytes
> 
> Looks like you're using the fourth when you want the first, possibly?

Nope.  Apparently, it's not well documented.  If you check PEP 358 
you'll find it.

~Ethan~



More information about the Python-list mailing list