[Python-3000] easy int to bytes conversion similar to chr?

Gregory P. Smith greg at electricrain.com
Thu Aug 23 08:54:08 CEST 2007


On Wed, Aug 22, 2007 at 11:12:32PM -0700, Gregory P. Smith wrote:
> Is there anything similar to chr(65) for creating a single byte string
> that doesn't involve creating an intermediate string or tuple object?
> 
>  bytes(chr(65))
>  bytes((65,))
> 
> both seem slightly weird.
> 
> Greg

yes i know.. bad example.  b'\x41' works for that.  pretend i used an
integer variable not an up front constant.

 bytes(chr(my_int))    # not strictly correct unless 0<=my_int<=255
 bytes((my_int,))
 struct.pack('B', my_int)

This came up as being useful in unittests for the bsddb bytes:bytes
changes i'm making but at the moment I'm not coming up with practical
examples where its important.  maybe this is a nonissue.

-gps


More information about the Python-3000 mailing list