2

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')?

1
  • Use bytes literal: b'\0'. bytes(padding_len) will give you padding_len bytes (filled with 0) Commented Aug 9, 2015 at 14:15

1 Answer 1

3
>>> 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Or b"\0" for that matter.
That works, but personally I wouldn't go there, unless the goal is to generate more questions. It's confusing that b'\0x' == b'\x00x' but b'\01' == b'\x01'
b'\0' is not confusing for a Python programmer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.