假设您拥有以下Python2代码:
#!/usr/bin/env python
import struct
struct.pack('s', 'hello')
这在Python2下工作正常,但它不会在Python3下运行,因为struct.pack的实现发生了变化。 struct.pack现在需要字节对象作为字符串标识符,而不再是字符串。在Python3下运行此代码的修复方法如下:
struct.pack('s', bytes('hello', 'utf-8'))
。但同样,这段代码不能在Python2下运行: - )
我尝试编码版本独立,因为我不想强迫任何人安装python2或3。
使这段代码版本独立的最佳方法是什么?
答案 0 :(得分:2)
Python 2 str
类型基本上已在Python 3中重命名为bytes
,而unicode
类型则变为str
。实质上,您将Python 3中的字节串和Python 3中的Unicode字符串发送到struct.pack()
。
可能正确的解决方法是在Python 2和3中使用Unicode(因此在使用struct.pack()
时始终进行编码,无论Python版本如何)。
另一种方法是使用isinstance测试:
value = 'hello'
if not isinstance(value, bytes):
vaule = value.encode('utf8')
这适用于Python 2和3,因为在Python 2中bytes
是str
的别名。