Heim  >  Artikel  >  Backend-Entwicklung  >  Python2.x版本中基本的中文编码问题解决

Python2.x版本中基本的中文编码问题解决

WBOY
WBOYOriginal
2016-06-10 15:07:511264Durchsuche

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 就行了。
实例(Python 2.0+)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

print "你好,世界";


输出结果为:

你好,世界

所以如果大家再学习过程中,代码中包含中文,就需要在头部指定编码。
注意:Python3.X 源码文件默认使用utf-8编码,所以可以正常解析中文,无需指定 UTF-8 编码。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn