Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #78100

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

From Peter Otten <__peter__@web.de>
Subject Re: pad binary string with a given byte value (python 3)
Date 2014-09-20 14:05 +0200
Organization None
References <541D5025.4070604@shopzeus.com>
Newsgroups comp.lang.python
Message-ID <mailman.14164.1411214758.18130.python-list@python.org> (permalink)

Show all headers | View raw


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?

bytes/str.ljust()

>>> def pad(b, n=16, c=b"\x0f"):
...     length = (len(b)+n-1)//n*n
...     return b.ljust(length, c)
... 
>>> pad(b"abc", 5)
b'abc\x0f\x0f'
>>> pad(b"abcde", 5)
b'abcde'
>>> pad(b"abcdef", 5)
b'abcdef\x0f\x0f\x0f\x0f'
>>> pad("abcde", 5, "*")
'abcde'
>>> pad("abcdef", 5, "*")
'abcdef****'

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: pad binary string with a given byte value (python 3) Peter Otten <__peter__@web.de> - 2014-09-20 14:05 +0200

csiph-web