[Python-Dev] PEP 461 - Adding % and {} formatting to bytes
Mark Lawrence
breamoreboy at yahoo.co.uk
Wed Jan 15 17:33:18 CET 2014
On 14/01/2014 19:56, Ethan Furman wrote:
> Duh. Here's the text, as well. ;)
>
> %s, because it is the most general, has the most convoluted resolution:
>
> - input type is bytes?
> pass it straight through
>
> - input type is numeric?
> use its __xxx__ [1] [2] method and ascii-encode it (strictly)
>
> - input type is something else?
> use its __bytes__ method; if there isn't one, raise an exception [3]
>
> Examples:
>
> >>> b'%s' % b'abc'
> b'abc'
>
> >>> b'%s' % 3.14
> b'3.14'
>
> >>> b'%s' % 'hello world!'
> Traceback (most recent call last):
> ...
> TypeError: 'hello world' has no __bytes__ method, perhaps you need
> to encode it?
>
For completeness I believe %r and %a should be included here as well.
FTR %a appears to have been introduced in 3.2, but I couldn't find
anything in the What's New and there's no note in the docs
http://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
to indicate when it first came into play.
--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.
Mark Lawrence
More information about the Python-Dev
mailing list