我正在努力移植一个库,使其与 python 2 和 3 兼容。该库从调用应用程序接收字符串或类似字符串的对象,我需要确保将这些对象转换为 unicode 字符串。
在 python 2 中我可以这样做:
unicode_x = unicode(x)
在 python 3 中我可以这样做:
unicode_x = str(x)
然而,我最好的跨版本解决方案是:
def ensure_unicode(x):
if sys.version_info < (3, 0):
return unicode(x)
return str(x)
这当然看起来不太好(尽管它有效)。有更好的解决方案吗?
我知道 unicode_literals
和 u
前缀,但这两种解决方案都不起作用,因为输入来自客户端并且不是我库中的文字。
最佳答案
不要重新发明兼容层轮子。使用 six
compatibility layer ,一个小型的单文件项目,可以包含在您自己的项目中:
Six supports every Python version since 2.6. It is contained in only one Python file, so it can be easily copied into your project. (The copyright and license notice must be retained.)
它包括一个 six.text_type()
callable正是这样做的,将值转换为 Unicode 文本:
import six
unicode_x = six.text_type(x)
在project source code这被定义为:
import sys
PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
# ...
if PY3:
# ...
text_type = str
# ...
else:
# ...
text_type = unicode
# ...
关于确保 python 2 和 3 中的 unicode 的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29213894/