简体   繁体   English

如何在python中从西班牙语进行编码和解码

[英]How to encode and decode from spanish in python

I have the following code written in python 2.7 我有以下代码用python 2.7编写

# -*- coding: utf-8 -*-    
import sys

_string = "años luz detrás"
print _string.encode("utf-8")

this throws the following error: 这会引发以下错误:

print _string.encode("utf-8")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)

Any help appreciated, thanks in advance 任何帮助表示感谢,提前谢谢

Add u before the " "之前加u "

>>> _string = u"años luz detrás"
>>> print _string.encode("utf-8")
años luz detrás

This would do. 这样做。

In Python 2 a string literal "" creates a bytestring. 在Python 2中,字符串文字""创建一个字节串。 Then you call .encode("utf-8") on a bytestring, Python tries first to decode it into Unicode string using a default character encoding ( ascii ) before executing .encode("utf-8") . 然后在字节串上调用.encode("utf-8") ,Python在执行.encode("utf-8")之前首先尝试使用默认字符编码( ascii )将其解码为Unicode字符串。

u"" creates Unicode string. u""创建Unicode字符串。 It will fix the UnicodeDecodeError as @Bleeding Fingers suggested . 它将修复UnicodeDecodeError作为@Bleeding Fingers建议

# -*- coding: utf-8 -*-    
print u"años luz detrás"

It might lead to UnicodeEncodeError if stdout is redirected. 如果重定向stdout,则可能导致UnicodeEncodeError Set PYTHONIOENCODING environment variable in this case. 在这种情况下设置PYTHONIOENCODING环境变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM