【发布时间】: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