成功解决 BUG:SyntaxError: Non-UTF-8 code starting with ‘\xe4’ in file G:/PythonDemo/test.py on line 2
异常解读
在 Python 代码编写过程中,会出现如下错误:
SyntaxError: Non-UTF-8 code starting with ‘\xe4’ in file G:/PythonDemo/test.py on line 2
该错误翻译为中文是:
代码文件的编码声明与实际使用的字符编码不匹配导致。
实际编码错误如下图所示。
解决思路
既然是编码错误,那只需要设置代码文件编码即可。
在代码文件的开头添加正确的编码声明:
# -*- coding: utf-8 -*-
不过一般的编辑器都支持 UTF-8 编码了,出现该错误的频率并不高,除了 UTF-8 还有其他编码可以添加到文件中。
# -*- coding: latin-1 -*-
上述配置指定了文件的编码为 Latin-1(ISO-8859-1)
错误复现
可以在 Python 文件中输入如下代码,即可出现本文标题所示错误:
print("Hello, World!")
print("äöüß")
代码出错原因
在上述代码中,使用了一个非 UTF-8 字符 'äöüß'
,它包含了一些德语特殊字符。由于没有指定编码方式,Python 解释器会尝试使用默认的 UTF-8 编码来解析代码文件。由于这个文件中包含了无法用 UTF-8 编码表示的字符,因此会导致错误。
错误信息如下
File "G:/PythonDemo/test.py", line 2
SyntaxError: Non-UTF-8 code starting with '\xe4' in file G:/PythonDemo/test.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
其他学习资料
- 《滚雪球学 Python》专栏与实体书:https://dream.blog.csdn.net/article/details/131268344
- 《爬虫 100 例》:https://blog.csdn.net/hihell/category_9280209.html
- 《Python 爬虫 120》:https://blog.csdn.net/hihell/category_11079529.html