我正在写一些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

当前回答

我也有同样的问题,只是把这个添加到我的文件顶部(在Python 3中我没有这个问题,但在Python 2中有

#!/usr/local/bin/python
# coding: latin-1

其他回答

我很长时间都找不到问题所在,但后来我意识到我从web中复制了一行“UTC-12:00”,其中的连字符/破折号导致了问题。我再写一遍“-”,问题就解决了。

有时候复制粘贴行也会出错。在这种情况下,只需重写复制粘贴的代码,它就可以工作。在重写时,它看起来像什么都没有改变,但错误将会消失。

更改文件字符编码,

把下面的行放在你的代码顶部

# -*- coding: utf-8 -*-

对我来说,这个问题是由引号中的“’”符号引起的。由于我从pdf文件中复制了代码,导致了这个错误。我只是把"'"换成了这个"'"。

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

我试图解析那个奇怪的窗口引号和尝试几件事后,这里是工作的代码片段。

def convert_freaking_apostrophe(self,string):

   try:
      issuer_rename = string.decode('windows-1252')
   except:
      issuer_rename = string.decode('latin-1')
   issuer_rename = issuer_rename.replace(u'’', u"'")
   issuer_rename = issuer_rename.encode('ascii','ignore')
   try:
      os.rename(directory+"/"+issuer,directory+"/"+issuer_rename)
      print "Successfully renamed "+issuer+" to "+issuer_rename
      return issuer_rename
   except:
      pass

#HANDLING FOR FUNKY APOSTRAPHE
if re.search(r"([\x90-\xff])", issuer):
   issuer = self.convert_freaking_apostrophe(issuer)