【问题标题】:Best way to port over Python 2.7 byte strings to Python 3将 Python 2.7 字节字符串移植到 Python 3 的最佳方式
【发布时间】:2019-09-25 15:34:20
【问题描述】:

我目前正在将 Python 2.7 代码移植到 Python 3,但我无法确定处理字符串的最佳方法。

我有具有以下导入的 Python 脚本:

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals

现在,由于 unicode_literals 转换了我在 Python 2.7 脚本中的所有字符串,我的脚本中出现了这样的错误:

TypeError: expecting a string or number, unicode found
TypeError: Argument 'key' has incorrect type (expected str, got unicode)

现在我可以通过简单地将 .encode('utf-8') 添加到每个字符串来摆脱 Python2.7 中的错误。例如:

scanline_node['projection_mode'].setValue("uv")
TypeError: expecting a string or number, unicode found
scanline_node['projection_mode'].setValue("uv".encode('utf-8'))

我的问题是,当我开始使用 Python 3 时,这是行不通的,因为它会将字符串的类型转换为字节。

我的问题是,处理此类问题的最佳方法是什么,以便我的代码可以在 Python 2.7 和 Python 3 上运行?我应该只使用内置的 str() 吗?

谢谢!

贾里德

【问题讨论】:

    标签: python python-3.x python-2.7 porting


    【解决方案1】:

    您应该使用six 库。它有助于代码在 Python 2 和 3 上运行。Six 包含一个名为 six.text_type 的类型,在 Python 2 上为 unicode,在 Python 3 上为 str。然后您可以将其用作函数期望的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-26
      • 2015-06-09
      • 1970-01-01
      相关资源
      最近更新 更多