Lesson03

xiaoxiao2021-02-28  160

常见编码:

ASCII:单字节 GB2312:简体中文编码集 GBK:兼容扩展了GB2312,能显示繁体中文,能显示日文中的片假名。 Unicode:国际组织制定的可以容纳世界上所有文字和符号的字符编码方案。每个字符占用2个字节。 UTF-8:是最流行的一种对 Unicode 进行传播和存储的编码方式。可变长度,比如英文字符和数字占1个字节,汉字占3个字节。 现在普遍应用:本机存储用Unicode,网络传输用utf-8

python解释器中:

python2 默认编码格式为 ascii python3 默认编码格式为Unicode (下面对于python编码设计的方面和查看系统编码格式来自博客:http://www.cnblogs.com/fnng/p/5008884.html)

在开发python程序过程中,会涉及到三个方面的编码:

python程序的编码 python程序运行环境的编码 python程序读取外部文件、网页的编码

python程序的编码:

首行加:# -*- coding: utf-8 -*-

python程序运行时环境(IDE)的编码:

执行下面一段代码: #!/usr/bin/env python # -*- coding: utf-8 -*- #python3 代码,wing ware 5 编辑 name = "你好" print(name) 在Windows cmd下执行时,出现下面问题: 因为Windows cmd的编码默认是 936(cmd框顶部右键——属性——选项——当前代码页),而python代码中编码格式为utf-8。 在cmd中输入:chcp 65001 回车执行(Windows cmd下,65001 表示utf-8),cmd顶部,右键——属性——字体设置为 Lucida Console,再来执行python程序就正常了。 (把字体重新设置为点阵字体,cmd中输入:chcp 936 回车执行,cmd回到原来设置了)

python程序读取外部文件、网页的编码:

暂时没找到合适的例子

查看python系统编码:

(python2 方法一样)

编码格式的转变:decode()与encode()

encode():把Unicode编码格式的字符串转换为其他编码格式的字符串 decode(): 将其他编码的字符串换成Unicode编码的字符串

代码:

#!/usr/bin/env python # -*- coding: utf-8 -*- #python3 代码,wing ware 5 编辑 #ord("单个字符") 查看字符对应的编码 print("字符a的编码为:",ord("a")) #chr(整数n) 查看整数n 对应的字符 print("编码97对应的字符为:",chr(97)) #查看单个汉字对应的编码 print("汉字你对应的编码为:",ord("你")) #查看编码对应的汉字 print("编码20320对应的字为:",chr(20320)) #python3默认的编码格式是Unicode #encode("编码格式a") 把Unicode编码格式转换为 编码格式a #decode("编码格式a") 把编码格式为 编码格式a 的字符串 转换为编码格式为Unicode的字符串 str1 = "你好啊" # encode("utf-8") 把Unicode编码格式转为utf-8编码格式 print("{_str1} 转换为utf-8编码格式后为:".format(_str1=str1),str1.encode("utf-8")) str2 = "hello" print("{_str2} 转换为utf-8编码格式后为:".format(_str2=str2),str2.encode("utf-8")) str3 = "hello你好啊" print("{_str3} 转换为utf-8编码格式后为:".format(_str3=str3),str3.encode("utf-8")) # encode("utf-8") 把utf-8格式转为Unicode str4 = str3.encode("utf-8") print("str4为:",str4) print("编码格式为utf-8的str4,转换为编码格式Unicode后为:",str4.decode("utf-8")) # 网络数据传输时会用到这两种转换

运行结果:

字符a的编码为: 97 编码97对应的字符为: a 汉字你对应的编码为: 20320 编码20320对应的字为: 你 你好啊 转换为utf-8编码格式后为: b'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a' hello 转换为utf-8编码格式后为: b'hello' hello你好啊 转换为utf-8编码格式后为: b'hello\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a' str4为: b'hello\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95\x8a' 编码格式为utf-8的str4,转换为编码格式Unicode后为: hello你好啊
转载请注明原文地址: https://www.6miu.com/read-45834.html

最新回复(0)