欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python中文编码知识点

程序员文章站 2023-12-03 17:17:40
如何用 python 输出 "hello, world!",英文没有问题,但是如果你输出中文字符"你好,世界"就有可能会碰到中文编码问题。 python 文件中如果未指定...

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

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

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

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 的 = 号两边不要空格。

#!/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中文编码知识点