pad binary string with a given byte value (python 3)

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Sep 20 08:12:39 EDT 2014


Nagy László Zsolt wrote:

>  >>> BS = 16
>  >>> pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
>  >>> pad('L')
> 'L\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f'
>  >>> pad(b'L')
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
>    File "<stdin>", line 1, in <lambda>
> TypeError: can't concat bytes to str
> 
> How do I write this function so it can pad byte strings? chr(charcode)
> creates a normal string, not a binary string.
> 
> I can figure out way for example this:
> 
>  >>> b'T'+bytearray([32])
> 
> but it just don't seem right to create a list, then convert it to a byte
> array and then convert it to a binary string. What am I missing?

You don't need to write your own function, just use the relevant string and
bytes methods. Use the ljust and rjust (left and right justify) methods:

To add padding on the left, justify on the right, and vise versa:

py> "Hello".ljust(20, "\x0f")
'Hello\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f'
py> "Hello".rjust(20, "\x0f")
'\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0fHello'

(The default fill character is space.)

The same works for bytes, except you have to make sure your fill char is
also a byte:

py> b"Hello".rjust(20, b"\x0f")
b'\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0fHello'
py> b"Hello".ljust(20, b"\x0f")
b'Hello\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f\x0f'



-- 
Steven




More information about the Python-list mailing list