I needed to add some padding to a bytes string. This is what I came up with:
if padding_len > 0:
data += bytes.fromhex('00') * padding_len
Is there a nicer way of representing a null byte in Python 3 than bytes.fromhex('00')?
>>> bytes.fromhex('00') == b'\x00'
True
>>> b'\x00' * 10
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
EDIT:
As hobbs points out in a comment below, it is certainly possible to use b'\0' instead of b'\x00' and as j-f-sebastian points out, it is not confusing in this instance.
But I wouldn't do it, anyway. It certainly works in this context (and it saves you two characters, if that's important). It will even work in the most common other context, where you are building strings for C and putting a null byte at the end.
But in the most general case, it can lead to confusion, because the compiler's interpretation of b'\0' is highly data dependent. In other words, it changes according to what comes after that zero.
>>> b'\0ABC' == b'\00ABC'
True
>>> b'\0ABC' == b'\000ABC'
True
>>> b'\0ABC' == '\0000ABC'
False
If you are debugging late at night when not all your brain cells are functioning, it is highly frustrating to have the length of a string change because you replaced a character in the string. All you have to do to avoid this is to always use two extra characters. It doesn't matter whether you use \x00 (hexadecimal) or \000 octal -- both of those will work properly no matter the value of the following character.
b"\0" for that matter.b'\0x' == b'\x00x' but b'\01' == b'\x01'b'\0' is not confusing for a Python programmer.
b'\0'.bytes(padding_len)will give you padding_len bytes (filled with 0)