我正在将一个程序从Python 2移植到Python 3。当值是字节时,我在处理%(插值)运算符时遇到了困难。
假设我们需要移植Python2中的这个表达式:'%s: %s\r\n' % (name, value)。
在程序的移植版本中,name和value的类型为bytes。结果也应该是bytes类型。在Python 3中,二进制插值仅计划用于Python 3.5 (PEP 460)。所以,我不确定我是否正确,但只有两种方法来处理这个问题--连接或字符串编码/解码:
>>> 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'对我来说,这两个解决方案都有点丑陋。当值为bytes时,是否有一些关于如何移植字符串格式的约定/建议
注意:不应该使用2to3工具,程序应该可以在Python2和Python3下运行。
发布于 2015-05-20 17:24:03
对于CPython,我制作了bttf库,我将添加一些移植功能;目前它支持将3.5字节的格式化代码添加到Python3.3ad3.4中:
因此,在您拥有以下内容之前:
>>> b'I am bytes format: %s, %08d' % (b'asdf', 42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'bytes' and 'tuple'并使用bttf
>>> from bttf import install
>>> install('bytes_mod')
>>> b'I am bytes format: %s, %08d' % (b'asdf', 42)
b'I am bytes format: asdf, 00000042'与__future__不同,打补丁是解释器范围的。
发布于 2014-06-02 16:36:10
在这种特殊情况下,解码-格式化-编码解决方案可能看起来很丑陋,但它显然是惯用的。
其思想是,您只在内部操作Unicode字符串,并在接收/发送数据时进行解码/编码。这种方法在Ned Batchelder's "Pragmatic Unicode"中被称为"Unicode三明治“。
此外,根据上下文,您可能只想更改name和value是bytes对象的事实。
https://stackoverflow.com/questions/23990241
复制相似问题