综述:python中字符串分为字节字符和非字节字符
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中输入字符串默认使用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'>
相关文章
- 【转载】不得不知道的Python字符串编码相关的知识
- Python字符串和编码
- python 应用 base64、hmac、hashlib包实现:MD5编码 base64编码解码、SHA256编码、urlsafe_b64encode编码等等基本所有的加密签名的方法
- Python字符串编码问题
- python,字符串方法
- 利用Python从文件中读取字符串(解决乱码问题)
- Python文件中头部的 #!(shebang) 基本解释
- python3 json数据格式的转换(dumps/loads的使用、dict to str/str to dict、json字符串/字典的相互转换)
- (方法总结)Python 一行代码提取字符串每个单词首字母的两种方法
- Python:字符串中的大小写转换