2016-06-11 30 views
1

Python 2 strbytes兼容,但在Python 3 strunicode如何使字符串解釋爲字節?

我正在將一些項目移植到Python3,但支持Python2.7。 這個prodject有許多字符串常量的測試。 '...'.join(...)'...'.format(...)也很少。

如何使Python3變爲b'123' == '123'

+3

你不能。相反,顯式編碼爲字節。 –

+0

爲了獲得從Py2.6到3.x的兼容性,你可以考慮使用'from __future__ import unicode_literals' – John1024

+0

'unicode_literals'我需要重寫常量,但我不知道與字節比較,從字符串lib返回的字符串。 – eri

回答

3

在PY3

>>> '123ü'.encode('utf-8') 
b'123\xc3\xbc' 

>>> bytes('123ü', 'utf-8') 
b'123\xc3\xbc' 

但你可能想擁有它周圍的其他方法,並使用UTF-8的Py2更容易過渡。使用

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals` 

在Py2中使所有字符串都爲u''

+1

我想反轉'unicode_literals' – eri