Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Python 2.7字节字符串移植到Python 3的最佳方法_Python_Python 3.x_Python 2.7_Porting - Fatal编程技术网

将Python 2.7字节字符串移植到Python 3的最佳方法

将Python 2.7字节字符串移植到Python 3的最佳方法,python,python-3.x,python-2.7,porting,Python,Python 3.x,Python 2.7,Porting,我目前正在将Python2.7代码移植到Python3上,我很难确定处理字符串的最佳方法 我有Python脚本,其中包含以下导入: from __future__ import print_function from __future__ import division from __future__ import absolute_import from __future__ import unicode_literals 现在,由于unicode_文本在Python 2.7脚本中转换了我的

我目前正在将Python2.7代码移植到Python3上,我很难确定处理字符串的最佳方法

我有Python脚本,其中包含以下导入:

from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
现在,由于unicode_文本在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'))
我的问题是,当我开始使用Python3时,这将不起作用,因为它会使字符串类型变成字节

我的问题是,处理这类问题的最佳方法是什么,这样我的代码就可以在Python2.7和Python3上工作?我应该使用内置str吗

谢谢

贾里德

你应该使用图书馆。它有助于代码在Python2和Python3上工作。Six包含一个名为unicode的类型,在Python2上为unicode,在Python3上为str。然后,您可以将其用作函数所期望的类型