在python 2.x中,有一些名为unicode
的unicode字符串和名为str
的字节串,这些字符串经常被误用于文本数据,因为它是默认值。幸运的是,python 3.x通过默认为py2 unicode
并让用户在处理二进制数据或编码的文本时选择了py2 str
来解决这个问题。但它也将py2 unicode
重命名为str
,将py2 str
重命名为bytes
。
我知道为3.x和2.x编写代码的许多方法可以区分它们但我想知道关于哪种方法最好以及为什么和可能学习方法的其他意见我还不知道。我也知道某些方法可能更适合某些情况,所以请随意在答案中公开所有这些方法。
这个问题也让我帮助别人选择最好的选择,但我被提醒这是一个意见问题。
以下是我所知道的方式......
使用""的类型并将其强制为unicode类型:
from __future__ import unicode_literals
if isinstance(string, type("")):
...
捕获NameError异常并使用特定于版本的代码。
认为似乎没有工作......
使用getattr()
检查encode()
和decode()
方法,因为Python 2.x似乎对这两种类型都使用了这两种方法。
由于我无法再添加任何答案,以下是我最终要使用的内容:
# Ensure compatibility with Python < 2.7 (2.7 uses bytes as an alias for str).
if 'bytes' not in vars():
bytes = str
if isinstance(name, bytes):
...byte string...
else:
...unicode string...
答案 0 :(得分:3)
考虑使用six,它旨在解决此问题和其他2到3迁移问题。
我仍然建议您提到的from __future import unicode_literals
声明,只是为了确保来自您自己来源的字符串得到一致处理,但对于其他所有内容,您可能会发现string-related constants in six有用:
six.text_type
评估为3中的str
和2中的unicode
。six.binary_type
评估为3中的bytes
和2中的str
。six.string_types
可用于isinstance
检查并评估为3中的str
和2中的basestring
。