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

当前回答

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

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

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

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

其他回答

或者你可以简单地用:

# coding: utf-8

在.py文件的顶部

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

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

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

你会得到一个游离的字节。你可以通过跑步找到它

with open("x.py") as fp:
    for i, line in enumerate(fp):
        if "\xe2" in line:
            print i, repr(line)

你应该用你的程序名替换"x.py"。您将看到行号和有问题的行。例如,在任意插入字节后,我得到:

4 "\xe2        lb = conn.create_load_balancer('my_lb', ['us-east-1a', 'us-east-1b'],[(80, 8080, 'http'), (443, 8443, 'tcp')])\n"

这里有很多好的解决方案。

其中没有真正解决的一个挑战是如何从视觉上识别某些难以识别的与其他纯ASCII字符相似的非ASCII字符。例如,破折号看起来几乎完全像连字符,大括号看起来很像直引号,这取决于文本编辑器的字体。

这一行代码应该在Mac或Linux上运行,它将剥离不在ASCII可打印范围内的字符,并并排显示差异:

# assumes Bash shell; for Bourne shell (sh), rearrange as a pipe and
# give '-' as second argument to 'sdiff' instead
sdiff --suppress-common-lines script.py <(tr -cd '\11\12\15\40-\176' <script.py)

字符\11、\12和\15分别是八进制的制表符、换行符和回车符;剩余的范围是可见的ASCII字符。(帽尖)

从这个SO线程中收集到的另一个技巧使用了一个逆字符类,由ASCII可见范围之外的任何内容组成,并突出显示它:

grep --color '[^ -~]' script.py

对于grep的macOS / BSD版本,这也可以很好地工作。