Python Forum
how to do a bytes f-string? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: how to do a bytes f-string? (/thread-28345.html)



how to do a bytes f-string? - Skaperen - Jul-15-2020

how to do a bytes f-string?


RE: how to do a bytes f-string? - menator01 - Jul-15-2020

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'>



RE: how to do a bytes f-string? - Skaperen - Jul-16-2020

i don't follow.

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


RE: how to do a bytes f-string? - bowlofred - Jul-16-2020

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.



RE: how to do a bytes f-string? - Skaperen - Jul-16-2020

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.