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

Viewed 25439

I'm looking for a formatted byte string literal. Specifically, something equivalent to

name = "Hello"
bytes(f"Some format string {name}")

Possibly something like fb"Some format string {name}".

Does such a thing exist?

5 Answers

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+).

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.

Related