简体   繁体   中英

Proper way to pack a string in python

What is the correct way to pack a five-byte asci string into python so that it is 8-bytes and little endian? For example, something like:

from struct import pack
pack('<ccccc3x', 'David')

Or:

pack('<ccccc3x', b'D', b'a', b'v', b'i', b'd')
# this works but seems unreadable to me

What would be the correct (or simplest) way to do this? Ideally, something like:

>>> pack('<ccccc3x', *bytearray(b'David'))

But it seems I cannot pass a list or do variable-unpacking and I have to do a new positional argument for every character.


The best I can come up with is the following, but I'm hoping there's a better way to do it:

# why won't it allow me to use `c`(har) and only `b`(yte) ?
>>> pack('<5b3x', *bytearray(b'David'))
b'David\x00\x00\x00' 

Update : seems like this might be the best way:

>>> pack('<5s3x', b'David')
b'David\x00\x00\x00'

Not sure though about all the different 'char'-ish types: s , b , and c from the struct page.

Endianness only is a thing for values more than a byte in size, so you don't need to worry about it here.

The most succinct way I can think of to pad a 5-byte bytestring to 8 bytes is

b'David'.ljust(8, b'\0')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM