Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine string subtypes in Python like bf"Hello, {name}!" [duplicate]

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?

like image 256
Enrico Borba Avatar asked May 10 '26 04:05

Enrico Borba


1 Answers

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.

like image 91
jwodder Avatar answered May 12 '26 18:05

jwodder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!