I am porting a program from Python 2 to Python 3. I am having difficulties dealing with % (interpolation) operator, when values are bytes.
Suppose we need to port this expression from Python 2: '%s: %s\r\n' % (name, value).
name and value in the ported version of the program are of type bytes. The result should be of type bytes too. In Python 3 binary interpolation is only planned for Python 3.5 (PEP 460). So, not sure if I am correct, but there are only two ways to deal with this problem -- concatenation or string encoding/decoding where appropriate:
>>> name = b'Host'
>>> value = b'example.com'
>>> # Decode bytes and encode resulting string.
>>> ('%s: %s\r\n' % (name.decode('ascii'), value.decode('ascii'))).encode('ascii')
b'Host: example.com\r\n'
>>> # ... or just use concatenation.
>>> name + b': ' + value + b'\r\n'
b'Host: example.com\r\n'
As for me, both of these solutions are a bit ugly. Is there some convention/recommendation about how to port string formatting, when values are bytes?
Note 2to3 tool shouldn't be used and the program should work under both Python 2 and 3.
formatstring method instead? E.g. '{0}: {1}\r\n'.format(name, value)`bytesdon't haveformatmethod. So you still need always to encode/decode.'{0}: {1}\r\n'is not a bytes, isn't it?str(name)will be"b'Host'".