Python:编码出现“Non-UTF-8 code starting with '\xd9'”错误解决方法

本文最后更新于:2024年2月19日 晚上

1、问题现象

在执行程序是,出现Non-UTF-8 code starting with '\xd9'异常:

image-20240117102517113

报错信息:

image-20240117102635117

通过异常信息,发现在首行出现了编码错误,非UTF-8编码,因而导致执行错误。通过错误信息,查询官方文档,查看右侧的链接:http://python.org/dev/peps/pep-0263/

2、问题原因

通过查看官方文档发现,在没有给出其他编码提示,Python 将默认使用 ASCII 作为标准编码,当编码存在冲突时出现上述错误:

image-20240117102857483

image-20240117103006624

3、解决方法

解决此类编码问题,可通过在首行引入固定的头来指定编码方式,在第一行加入编码注释:

1
2
3
4
5
6
7
8
9
10
11
# <--格式一-->
# coding=<encoding name>

# <--格式二-->
#!/usr/bin/python
# -*- coding: <encoding name> -*-


# <--格式三-->
#!/usr/bin/python
# vim: set fileencoding=<encoding name> :

<encoding name>说明脚本运行的编码格式。

示例:按照格式二指定为utf-8编码方式

1
2
#!/usr/bin/python
# -*- coding: <utf-8> -*-

补充头注释说明编码方式为utf-8后,便能正常执行:

image-20240117103429509


Python:编码出现“Non-UTF-8 code starting with '\xd9'”错误解决方法
http://www.codestar.top/2024/02/19/Python/Python:编码出现“Non-UTF-8-code-starting-with-xd9-”错误解决方法/
作者
mini小新
发布于
2024年2月19日
更新于
2024年2月19日
许可协议