SyntaxError: Non-ASCII character '\xe4' in file today.py on line 2, but no encoding declared;

当Python文件中出现非ASCII字符且未声明编码时,会抛出SyntaxError。为解决此问题,可以将源代码设置为UTF-8编码。方法包括:1. 在文件开头添加魔法注释作为编码声明;2. 使用符合UTF-8的文本编辑器保存文件;3. 确保编辑器配置正确。Python默认标准编码为ASCII,除非另有声明。

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

error detail: 

% python today.py
  File "today.py", line 2
SyntaxError: Non-ASCII character '\xe4' in file today.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

solutions:

take UTF-8 as an example.

First:

#!/usr/bin/python
#coding:utf-8
from datetime import datetime
print(datetime.now().strftime('今天是%Y年%m月%d日'))

Second:

#!/usr/bin/python
#-*-coding:utf-8 -*-
from datetime import datetime
print(datetime.now().strftime('今天是%Y年%m月%d日'))

Third:

#!/usr/bin/python
#vim: set fileencoding:utf-8
from datetime import datetime

print(datetime.now().strftime('今天是%Y年%m月%d日'))

 Note: 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

 

references:

1. https://www.python.org/dev/peps/pep-0263/

2. https://www.fatalerrors.org/a/syntaxerror-non-ascii-character-but-no-encoding-declared.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值