Python如何解决字符串中的Unicode错误

时间:2016-08-17 22:30:20

标签: python unicode utf-8

我遇到了经典错误:

  

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")。没有任何效果。任何建议都会有所帮助。

1 个答案:

答案 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("é")
  • 相同
  • 您通常使用py2 str调用decode,并使用py2 unicode进行编码。
    • 由于早期的设计问题,你可以同时打电话给两者,即使这没有任何意义。
    • 在python3中,str(与python2 unicode相同)无法再解码,因为根据定义,字符串是已解码的字节序列。默认情况下,它使用utf-8编码。
  • 在ascii编解码器中编码的字节序列与其解码的对应序列完全相同。
    • 在没有将来导入的python 2.7中: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习语的安全别名。
    • 由于我以外的原因,软件包本身名为&#34; future&#34;,因此要安装您运行的builtins模块:pip install future
  • from builtins import str具有以下效果:
    • str构造函数现在提供您的想法,即以python2 unicode对象形式的文本数据。因此它在功能上与str = unicode
    • 相同
    • 注意:Python3 str在功能上与Python2 unicode
    • 相同
    • 注意:要获取字节,可以使用&#34;字节&#34;前缀,例如b'é'

外卖是这样的:

  1. 早期对读取/解码进行解码,最后对写入/编码进行编码
  2. str个对象用于字节,将unicode个对象用于文本