我遇到了经典错误:
ascii'编解码器无法解码位置28中的字节0xc3:序数不在 范围(128)
这一次,我无法解决它。错误来自这一行:
mensaje_texto_inmobiliaria = "%s, con el email %s y el teléfono %s está se ha contactado con Inmobiliar" % (nombre, email, telefono)
具体来说,来自teléfono
字。我尝试将# -*- coding: utf-8 -*-
添加到文件的开头,添加unicode( <string> )
和<string>.encode("utf-8")
。没有任何效果。任何建议都会有所帮助。
答案 0 :(得分:3)
这是为了回答为什么这解决了OP所遇到的问题,以及关于问题OP正在尝试描述的一些背景
from __future__ import unicode_literals
from builtins import str
在默认的iPython 2.7内核中:
(iPython会话)
In [1]: type("é") # By default, quotes in py2 create py2 strings, which is the same thing as a sequence of bytes that given some encoding, can be decoded to a character in that encoding.
Out[1]: str
In [2]: type("é".decode("utf-8")) # We can get to the actual text data by decoding it if we know what encoding it was initially encoded in, utf-8 is a safe guess in almost every country but Myanmar.
Out[2]: unicode
In [3]: len("é") # Note that the py2 `str` representation has a length of 2. There's one byte for the "e" and one byte for the accent.
Out[3]: 2
In [4]: len("é".decode("utf-8")) # the py2 `unicode` representation has length 1, since an accented e is a single character
Out[4]: 1
python 2.7中需要注意的其他一些事项:
"é"
与str("é")
u"é"
与"é".decode('utf-8')
或unicode("é", 'utf-8')
u"é".encode('utf-8')
与str("é")
str
调用decode,并使用py2 unicode
进行编码。
str
(与python2 unicode
相同)无法再解码,因为根据定义,字符串是已解码的字节序列。默认情况下,它使用utf-8编码。type("a".decode('ascii'))
提供了一个unicode对象,但这与str("a")
几乎完全相同。在python3中情况并非如此。话虽如此,这就是上面的代码片段:
__future__
是由核心python团队维护的模块,它将python3功能向后移植到python2,允许你在python2中使用python3习语。from __future__ import unicode_literals
具有以下效果:
"é"
与str("é")
"é"
在功能上与unicode("é")
builtins
是一个经核心python团队批准的模块,包含在python2中使用python3 api的python3习语的安全别名。
builtins
模块:pip install future
from builtins import str
具有以下效果:
str
构造函数现在提供您的想法,即以python2 unicode对象形式的文本数据。因此它在功能上与str = unicode
str
在功能上与Python2 unicode
b'é'
外卖是这样的:
str
个对象用于字节,将unicode
个对象用于文本