Python 3 byte formatting

In Python 3, you can format a string, for example:

"{0}, {1}, {2}".format(1, 2, 3) 

But how to format bytes?

 b"{0}, {1}, {2}".format(1, 2, 3) 

raises AttributeError: 'bytes' object has no attribute 'format' .

If there is no format method for bytes, how to format or overwrite bytes?

+44
python string-formatting
Mar 29 '13 at 19:54
source share
4 answers

And with 3.5 % formatting will work for bytes !

https://mail.python.org/pipermail/python-dev/2014-March/133621.html

+35
Mar 28
source share

Another way:

 "{0}, {1}, {2}".format(1, 2, 3).encode() 

Tested on IPython 1.1.0 and Python 3.2.3

+14
Jan 09 '14 at 13:20
source share

Interestingly, .format() not supported for byte sequences; as you demonstrated.

You can use .join() as suggested here: http://bugs.python.org/issue3982

 b", ".join([b'1', b'2', b'3']) 

There is a speed advantage associated with .join() using .format() shown by BDFL itself: http://bugs.python.org/msg180449

+12
Mar 29 '13 at 20:05
source share

I found that% a works best in Python 3.6.2, it should work for both b "and":

 print(b"Some stuff %a. Some other stuff" % my_byte_or_unicode_string) 
+4
Nov 09 '17 at 16:39 on
source share



All Articles