PyCharm 中文注释报错 SyntaxError: Non-ASCII character

本文介绍了解决Python程序中使用中文注释导致的编译错误的方法。默认情况下,Python源文件采用ASCII编码,不支持中文字符。通过在文件头部添加指定编码声明(如UTF-8),可以有效避免此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python菜鸟今天写程序时加了中文注释,竟然就报错了,头一回碰到注释报错,活久见。

平时看别人代码时,或多或少会碰到中文注释乱码问题,原因是不同文件编码格式,有些文件编码并不能显示中文,如ASCII。而PyCharm对于中文不仅仅是显示乱码问题,而是编译报错。如下

SyntaxError: Non-ASCII character '\xe6' in file TestPy3/t.py on line 19, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

看看提示的链接 http://python.org/dev/peps/pep-0263/

Defining the Encoding
    Python will default to ASCII as standard encoding if no other
    encoding hints are given.

    To define a source code encoding, a magic comment must
    be placed into the source files either as first or second
    line in the file, such as:

          # coding=<encoding name>

    or (using formats recognized by popular editors)

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

    or

          #!/usr/bin/python
          # vim: set fileencoding=<encoding name> :

大概意思是,默认文件是ASCII格式,需要更改文件编码,操作是在文件首行加上

#!/usr/bin/python
# -*- coding:utf8 -*-

编译运行,一切正常。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值