Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode and decode from spanish in python

I have the following code written in 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

like image 626
aledustet Avatar asked Jan 05 '14 15:01

aledustet


People also ask

How do you use encoding and decoding in Python?

decode() is a method specified in Strings in Python 2. This method is used to convert from one encoding scheme, in which argument string is encoded to the desired encoding scheme. This works opposite to the encode. It accepts the encoding of the encoding string to decode it and returns the original string.

How do I encode a Python code?

Python String encode() MethodThe encode() method encodes the string, using the specified encoding. If no encoding is specified, UTF-8 will be used.

What is encoding Latin in Python?

The latin-1 encoding in Python implements ISO_8859-1:1987 which maps all possible byte values to the first 256 Unicode code points, and thus ensures decoding errors will never occur regardless of the configured error handler.

How do you get the UTF-8 character code in Python?

UTF-8 is a variable-length encoding, so I'll assume you really meant "Unicode code point". Use chr() to convert the character code to a character, decode it, and use ord() to get the code point. In Python 2, chr only supports ASCII, so only numbers in the [0.. 255] range.


1 Answers

Add u before the "

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

This would do.

like image 91
Bleeding Fingers Avatar answered Sep 21 '22 23:09

Bleeding Fingers