Is there a formatted byte string literal in Python 3.6+?

No. The idea is explicitly dismissed in the PEP:

For the same reason that we don't support bytes.format(), you may not combine 'f' with 'b' string literals. The primary problem is that an object's __format__() method may return Unicode data that is not compatible with a bytes string.

Binary f-strings would first require a solution for bytes.format(). This idea has been proposed in the past, most recently in PEP 461. The discussions of such a feature usually suggest either

  • adding a method such as __bformat__() so an object can control how it is converted to bytes, or

  • having bytes.format() not be as general purpose or extensible as str.format().

Both of these remain as options in the future, if such functionality is desired.


In 3.6+ you can do:

>>> a = 123
>>> f'{a}'.encode()
b'123'

You were actually super close in your suggestion; if you add an encoding kwarg to your bytes() call, then you get the desired behavior:

>>> name = "Hello"
>>> bytes(f"Some format string {name}", encoding="utf-8")

b'Some format string Hello'

Caveat: This works in 3.8 for me, but note at the bottom of the Bytes Object headline in the docs seem to suggest that this should work with any method of string formatting in all of 3.x (using str.format() for versions <3.6 since that's when f-strings were added, but the OP specifically asks about 3.6+).