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

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'


From python 3.6.2 this percent formatting for bytes works for some use cases:

print(b"Some stuff %a. Some other stuff" % my_byte_or_unicode_string)

But as AXO commented:

This is not the same. %a (or %r) will give the representation of the string, not the string iteself. For example b'%a' % b'bytes' will give b"b'bytes'", not b'bytes'.

Which may or may not matter depending on if you need to just present the formatted byte_or_unicode_string in a UI or if you potentially need to do further manipulation.