.py文件中的西班牙语文本

2024-05-16 09:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

这是密码

A = "Diga sí por cualquier número de otro cuidador.".encode("utf-8")

我得到这个错误:

“ascii”编解码器无法解码位置6中的字节0xed:序号不在范围(128)内

我试了很多次编码都没有成功。

编辑:

我一开始就有这个了

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

更改为

A = u"Diga sí por cualquier número de otro cuidador.".encode("utf-8")

没有帮助


Tags: 密码字节错误编解码器asciide解码utf
3条回答

错误消息:'ascii' codec can't decode byte 0xed in position 6: ordinal not in range(128)

说第七个字节是0xed。这可能是某些(可能是CJK)高序数Unicode字符的UTF-8序列的第一个字节(这与所报告的事实完全不一致),也可能是用Latin1或cp1252编码的i-acute。我赌的是cp1252。

如果您的文件是用UTF-8编码的,那么有问题的字节不是0xed,而是0xc3

Preliminaries:
>>> import unicodedata
>>> unicodedata.name(u'\xed')
'LATIN SMALL LETTER I WITH ACUTE'
>>> uc = u'Diga s\xed por'

What happens if file is encoded in UTF-8:
>>> infile = uc.encode('utf8')
>>> infile
'Diga s\xc3\xad por'
>>> infile.encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6: ordinal not in range(128)
#### NOT the message reported in the question ####

What happens if file is encoded in cp1252 or latin1 or similar:
>>> infile = uc.encode('cp1252')
>>> infile
'Diga s\xed por'
>>> infile.encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 6: ordinal not in range(128)
#### As reported in the question ####

在代码开头使用# -*- coding: utf-8 -*-并不能神奇地确保您的文件是用UTF-8编码的——这取决于您和您的文本编辑器。

操作:

  1. 将文件另存为UTF-8。
  2. 作为 别人建议,你需要 废话

你在用Python 2吗?

在Python 2中,该字符串文本是一个bytestring。您试图对其进行编码,但只能对Unicode字符串进行编码,因此Python将首先尝试使用默认的“ascii”编码将bytestring解码为Unicode字符串。

不幸的是,字符串包含非ASCII字符,因此无法将其解码为Unicode。

最好的解决方案是使用Unicode字符串文字,如下所示:

A = u"Diga sí por cualquier número de otro cuidador.".encode("utf-8")

在代码的第一行输入:

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

相关问题 更多 >