脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python中文编码知识点

Python中文编码知识点

2021-05-29 00:35脚本之家 Python

在本篇文章里小编给大家分享了关于Python中文编码的相关知识点以及对应实例内容,有兴趣的朋友们学习下。

如何用 python 输出 "hello, world!",英文没有问题,但是如果你输出中文字符"你好,世界"就有可能会碰到中文编码问题。
python 文件中如果未指定编码,在执行过程会出现报错:

#!/usr/bin/python
print "你好,世界";

以上程序执行输出结果为:

?
1
2
file "test.py", line 2
syntaxerror: non-ascii character '\xe4' in file test.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

python中默认的编码格式是 ascii 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。
解决方法为只要在文件开头加入 # -*- coding: utf-8 -*- 或者 #coding=utf-8 就行了

注意:#coding=utf-8 的 = 号两边不要空格。

?
1
2
3
4
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
print "你好,世界";

输出结果为:

Python中文编码知识点

所以如果大家在学习过程中,代码中包含中文,就需要在头部指定编码。

注意:python3.x 源码文件默认使用utf-8编码,所以可以正常解析中文,无需指定 utf-8 编码。
注意:如果你使用编辑器,同时需要设置 py 文件存储的格式为 utf-8,否则会出现类似以下错误信息:

syntaxerror: (unicode error) ‘utf-8' codec can't decode byte 0xc4 in position 0:
invalid continuation byte

pycharm 设置步骤:

  • 进入 file > settings,在输入框搜索 encoding。
  • 找到 editor > file encodings,将 ide encoding 和 project encoding 设置为utf-8。

Python中文编码知识点

延伸 · 阅读

精彩推荐