如何理解Python编码格式的使用?

Python

1 Python编码格式的使用

1.1 Python的原文解析

– Python的源码文件默认编码是UTF-8
– 如果要使用非UTF-8的编码,应该使用特殊声明
– 编码标准可以参阅以下链接,https://docs.python.org/2.7/library/codecs.html#standard-encodings
注:Python要求执行文件声明的编码、文件使用的编码与文件中包含字符编码一致,否则报错

1.2 实操理解

1.2.1 创建对比脚本

1.2.1.1 创建脚本1

vim treated_encode.py

输入如下内容:

#!/usr/bin/python
# -*- coding: gb2312 -*-
print("Hello, World!")
print("你好!中国!")

注:
– 执行文件声明编码为GB2312
– 执行文件实际使用UTF-8编码
– 执行文件中包含非GB2312字符(英文字符)

1.2.1.2 创建脚本2

iconv -f utf-8 -t gb2312 treated_encode.py > gb2312_reated_encode.py
cat gb2312_reated_encode.py

脚本内容如下:

# -*- coding: gb2312 -*-
print("Hello, World!")
print("▒▒ã▒▒й▒")

注:
– 执行文件声明执行文件编码为GB2312
– 执行文件实际使用GB2312编码
– 执行文件中只包含GB2312字符

1.2.1.3 创建脚本3

cat treated_encode.py | grep -v gb2312 | grep -v 中国 > utf-8_reated_encode.py
cat utf-8_reated_encode.py

脚本内容如下:

#!/usr/bin/python
print("Hello, World!")

注:
– 执行文件声明编码为UTF-8(默认声明)
– 执行文件实际使用UTF-8编码
– 执行文件中只包含UTF-8字符

1.2.2 授予脚本的执行权限

chmod u+x *reated_encode.py

1.2.3 测试对比脚本

1.2.3.1 测试脚本1

./treated_encode.py

显示如下:

  File "./treated_encode.py", line 4
SyntaxError: 'gb2312' codec can't decode bytes in position 9-10: illegal multibyte sequence

注:
– 执行文件声明编码为GB2312
– 执行文件实际使用UTF-8编码
– 执行文件中包含非GB2312字符(英文字符)
– 执行结果失败

1.2.3.2 测试脚本2

./gb2312_reated_encode.py

显示如下:

Hello, World!
▒▒ã▒▒й▒

注:
– 执行文件声明执行文件编码为GB2312
– 执行文件实际使用GB2312编码
– 执行文件中只包含GB2312字符
– 执行结果通过

1.2.3.3 测试脚本3

./utf-8_reated_encode.py

显示如下:

Hello, World!

– 执行文件声明编码为UTF-8(默认声明)
– 执行文件实际使用UTF-8编码
– 执行文件中只包含UTF-8字符
– 执行结果通过

参阅文档:
https://docs.python.org/2.7/tutorial/index.html
https://docs.python.org/2.7/

没有评论

发表回复

FTP & SFTP & FTPS
如何使用Python连接FTP?

1 前言 一个问题,一篇文章,一出故事。 笔者遇到一个需要使用Python连接ftp的需求,于是整理 …

Python
如何安装部署pysmb?

1 基础知识 pysmb是一个实验性的SMB/CIFS库 pysmb用Python编写 pysmb实 …

Python
如何安装部署Anaconda3?

1 基础知识 1.1 Anaconda的版本 – Anaconda Enterprise …