我正在写一些python代码,我收到了标题中的错误消息,从搜索这与字符集有关。

这是导致错误的行

hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")

我不知道什么字符不是在ANSI ASCII集?此外,搜索“\xe2”并不能提供关于该字符显示为什么字符的更多信息。这一行中的哪个字符导致了问题?

我还看到了针对这个问题的一些修复程序,但我不确定该使用哪个。有人能澄清什么是问题(python不解释unicode,除非被告知这样做?),以及我将如何正确地清除它?

编辑: 这是出错的那条线附近的所有线

def createLoadBalancer():
    conn = ELBConnection(creds.awsAccessKey, creds.awsSecretKey)
    hc = HealthCheck("instance_health", interval=15, target808="HTTP:8080/index.html")
    lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])
    lb.configure_health_check(hc)
    return lb

当前回答

基于PEP 0263——定义Python源代码编码

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

其他回答

在花了大约半小时的时间查看堆栈溢出后,我突然意识到,如果在注释中使用单引号“'”将会通过错误:

SyntaxError: Non-ASCII character '\xe2' in file

在查看traceback后,我能够找到在我的评论中使用的单引号。

如果您想找出是什么字符导致了这个问题,只需将有问题的变量赋值给一个字符串,并在iPython控制台中打印它。

对我来说

In [1]: array = [[24.9, 50.5]​, [11.2, 51.0]]        # Raises an error

In [2]: string = "[[24.9, 50.5]​, [11.2, 51.0]]"     # Manually paste the above array here

In [3]: string
Out [3]: '[[24.9, 50.5]\xe2\x80\x8b, [11.2, 51.0]]' # Here they are!

当我在阅读文本文件时遇到类似的问题时,我使用…

f = open('file','rt', errors='ignore')

我的case \xe2是一个'它应该被'取代。

一般来说,我建议使用例如https://onlineasciitools.com/convert-utf8-to-ascii将UTF-8转换为ASCII

但是如果你想保持UTF-8,你可以使用

#-*- mode: python -*-
# -*- coding: utf-8 -*-

\xe2是'-'字符,它出现在一些复制和粘贴中,它使用了不同的等号'-',导致编码错误。 将'-'(来自复制粘贴)替换为正确的'-'(来自键盘按钮)。