綜述:python中字符串分為字節字符和非字節字符
python3
python3中默認輸入字符串以非字節字符編碼,使用unicode字符集表示,可以使用encode方法轉化為ascii,utf-8, utf-16等各種編碼形式的字節字符;因此僅非字節字符才被python3認為是標准字符串
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> uni_str = 'abc'
>>> type(uni_str)
<class 'str'>
>>> utf8_str = uni_str.encode('utf-8')
>>> type(utf8_str)
<class 'bytes'>
>>> asc_str = uni_str.encode('utf-8')
>>> type(asc_str)
<class 'bytes'>
>>> uni_str
'abc'
>>> utf8_str
b'abc'
>>> asc
asc_str ascii(
>>> asc_str
b'abc'
python2
python2中輸入字符串默認使用ascii編碼的字節字符,因此默認不支持中文(存疑),可以使用decode方法將默認字節編碼的字符串轉化為非字節字符,使用unicode字符集表示,進而使用encode方法將unicode字符集的非字節字符轉化為其他編碼形式的字符如utf-8, utf-16;因此編碼后字符串,即字節字符才被python2認為是字符串格式
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> str = 'abc'
>>> type(str)
<type 'str'>
>>> uni_str = str.decode('ascii')
>>> uni_str
u'abc'
>>> type(uni_str)
<type 'unicode'>
>>> utf8_str = uni_str.encode('utf-8')
>>> utf8_str
'abc'
>>> type(utf8_str)
<type 'str'>
