python - 在python 3.x和2.x中统一区分str/unicode和bytes/str的方法是什么?

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

<分区>

在 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...

最佳答案

考虑使用 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 .

关于python - 在python 3.x和2.x中统一区分str/unicode和bytes/str的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25934287/

相关文章:

python - FigureCanvasAgg' 对象没有属性 'invalidate' ? python 绘图

python - 为什么我需要 2 对括号来声明一个数字列表

c - c 编程中的字符串在输出末尾具有垃圾值

python-3.x - 神经网络预测第 n 个方格

python - 如何在 Python 中对单个函数执行多处理?

Python:读取和写入数百万个小文件的速度很慢

linux - 在csh中提取字符串

c++ - 指针可以用来遍历字符数组吗?

python-3.x - 正则表达式用于避免重复的连续字符,但排除一个特定字符

python-3.x - 有没有办法在 py2app 应用程序中使用 ffmpeg 二进制/unix 可执行文件在没有安装它的计算机上运行 ffmpeg?