Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Python的字符串编码

$
0
0
python2的编码

在Python2中,str和unicode都是basestring的子类。

str是unicode经过编码后的字节组成的序列。

utf-8编码的str是可变长度,节省空间。unicode占固定长度字节,浪费空间。所以网络传输或者保存文件通常会使用unf-8.

basestring /\ /\ /\ /\ /\ /\ /decode\ str-------->unicode <-------- encode('utf-8')

下面这段代码,展示了str和unicode的关系。

In [20]: s = 'hello' In [21]: isinstance(s, str) Out[21]: True In [24]: new_s = s.decode() In [25]: isinstance(s, unicode) Out[25]: False In [26]: isinstance(new_s, unicode) Out[26]: True Python3的编码

Python3中,字符串是以unicode编码的,就没有str和unicode了,只有str,用unicode编码。

用unicode表示的str,通过encode()方法可以编码为bytes。网络传输或文件保存使用bytes,节省空间。byte可以通过decode方法转换成unicode。

建议使用uft-8进行转换。注意,str和bytes是python的对象,utf-8是编码方式。

建议在开头添加这样的编码声明:

#!/usr/bin/env python3 # -*- coding: utf-8 -*-

实际上Python只检查#、coding和编码字符串,其他的字符都是为了美观加上的。

参考资料 Python字符编码详解 廖雪峰:字符串和编码 Python 字符编码判断

Viewing all articles
Browse latest Browse all 9596

Trending Articles