确保 python 2 和 3 中的 unicode 的 Pythonic 方法

标签 python python-3.x python-2.x

我正在努力移植一个库,使其与 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_literalsu 前缀,但这两种解决方案都不起作用,因为输入来自客户端并且不是我库中的文字。

最佳答案

不要重新发明兼容层轮子。使用 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/

相关文章:

python - 生成一个 10000 位的随机序列

python - 在 tkinter 中显示帧内的视频流

python - 如何创建持续时间总计列表?

python - struct.unpack 和 win/lin 中 python 2.4 和 2.4.4 的问题

python - 在 Python 中使用 raw_input 收集输入

python - 内置双星号电源功能未按预期工作

python - Pandas hub_table 与 aggfunc 在不同数据上的工作方式有所不同

python-3.x - 使用 unittest.mock 在 Python 中模拟 os.remove

python - 如何在 Python 中创建 session 变量?

python - 从排序列表创建字典