我的代码需要兼容Python 2.x和3.x版本。我将两个字符串作为函数的输入,并且我需要对它们进行一些操作:
if len(str1) > 10:
str1 = str1[:10] + '...'
if six.PY3:
return ' : '.join((str1, str2))
对于 Python 2.x,上面的连接给出错误:
UnicodeDecodeError:“ascii”编解码器无法解码位置 0 中的字节 0xc2:序数不在范围内(128)
对于 2.x 和 3.x 的所有版本,处理此类情况的更简洁的方法是什么? 由于这两个字符串都输入到我的代码中,因此我需要确保即使这些字符串中的任何一个包含 UTF-8 字符,它们也应该正确连接。
声明:我对 Python 非常陌生。
在 Python 3 中,您通常希望只处理
str
。这就是字符串的数据类型。它表达字符。这些字符不采用任何特定的编码;操作它们时,您不需要了解编码。 str1[:10]
表示“前10个字符”,无论是“abcdefghij”还是“文字化けは楽しいんだ”。
当编码为实际字节时,类型为
bytes
。您不想在操作文本时处理 bytes
。
在Python 2中,由于某些原因,Python 3中的
str
在Python 2中是unicode
。Python 3中的bytes
在Python 2中是str
。
Python 3 | Python 2 | 表达 |
---|---|---|
|
|
人物 |
|
|
字节 |
字符串文字
''
是 str
,在 Python 2 中它们是 str
(表示字节)。在 Python 2 中表达 unicode
的正确字符串文字是 u''
。 u''
仍然适用于 Python 3 并映射到 Python 3 str
;所以它们用两种语言表达基于字符的类型。
所以你想让它以两种语言运行是:
if len(str1) > 10:
str1 = str1[:10] + u'...'
return u' : '.join((str1, str2))
然后你要确保
str1
和 str2
在 Py3 中是 str
,在 Py2 中是 unicode
。如何做到这一点完全取决于他们来自哪里。