假设我有一个函数

def NewFunction():
    return '£'

我想打印一些东西,前面有一个磅号,当我试图运行这个程序时,它打印一个错误,显示这个错误消息:

SyntaxError: Non-ASCII character '\xa3' in file 'blah' but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details

有人能告诉我如何在返回函数中包含一个磅号吗?我基本上是在一个类中使用它,它是在'__str__'部分中,包含了磅号。


当前回答

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

其他回答

首先在文件开头添加# -*- coding: utf-8 -*-行,然后对所有非ascii码的unicode数据使用u'foo':

def NewFunction():
    return u'£'

或者使用Python 2.6以来可用的魔法使其自动:

from __future__ import unicode_literals

在.py脚本的顶部添加以下两行对我来说很有效(第一行是必要的):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

在脚本中添加以下两行为我解决了这个问题。

# !/usr/bin/python
# coding=utf-8

希望能有所帮助!

您可能正在尝试使用Python 2解释器运行Python 3文件。目前(截至2019年),在Windows和大多数Linux发行版上安装这两个版本时,python命令默认为python 2。

但如果你确实在Python 2脚本上工作,这个页面上还没有提到的解决方案是用UTF-8+BOM编码重新保存文件,这将在文件的开头添加三个特殊字节,它们将显式地通知Python解释器(和你的文本编辑器)文件编码。

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.