首页 技术 正文
技术 2022年11月15日
0 收藏 345 点赞 3,495 浏览 786 个字

Python2

在python中包含两种字符串类型:str和unicode,str并不是完全意义上的字符串,其实是由unicode经过编码(encode)后的字节组成的字节字符串,而unicode则是真正意义上的字符串,由字符组成。

python 在内部使用两个字节来存储一个unicode,使用unicode对象而不是str的好处,就是unicode方便于跨平台。

两种方式定义一个unicode:

u1 = u'你好'u2 = unicode('你好', 'utf-8')

Python2与python3中字符串的区别

str.decode方法和unicode.encode方法是最常用的:

要明白要处理的是str还是unicode, 使用对的处理方法(str.decode/unicode.encode)

Python2的默认编码(默认字符集)是 asscii

Python2与python3中字符串的区别

Python2与python3中字符串的区别

注意

str也能编码(encode),unicode也能解码(decode)unicode解码意义不大
str编码通常会报错:

Python2与python3中字符串的区别

代码报错,提示错误信息:UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe4 in position 0: ordinal not in range(128)

是因为没有指定defaultencoding,其实s.encode(‘utf-8’)是存在在一次隐式的decode:

Python2与python3中字符串的区别

默认编码:ascii是许多报错的原因,所以可以在代码设置默认编码(defaultencoding):

Python2与python3中字符串的区别

Python3

Python3的默认编码(默认字符集)是 utf-8

Python2与python3中字符串的区别

python3默认使用的是str类型对字符串编码,默认使用bytes操作二进制数据流,编码使用enocde, 解码使用的是decode

Python2与python3中字符串的区别

Python2与python3字符串差异比较

  字节码 字符串 默认编码
Python2 str unicode ascii
Python3 bytes str utf-8
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,129
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,601
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,444
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,218
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,852
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,940