Python Forum

Full Version: how to do a bytes f-string?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
how to do a bytes f-string?
Not sure if this is what you're asking

h = b'hello'
print(h)
print(type(h))

print(f'{h.decode()}')
h = h.decode()
print(type(h))
Output:
b'hello' <class 'bytes'> hello <class 'str'>
i don't follow.

i wanted to do:
x = b'xyzzy'
s = bf'foo{x}bar'
but that is a syntax error.
Not available. From the docs

Quote:A string literal with 'f' or 'F' in its prefix is a formatted string literal; see Formatted string literals. The 'f' may be combined with 'r', but not with 'b' or 'u', therefore raw formatted strings are possible, but formatted bytes literals are not.

And the pep for f-strings talks about the rationale here.

Quote:No binary f-strings

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 [11]. 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.
my suggestion is for bytes formatting getting a non-bytes unicode character to raise an exception.

the other thing i have a need for is a non-literal f-string. that is, a way to process a regular string that has contents that would be work in a literal f-string, but do it with that non-literal string value.