Encode Python ASCII

2

Hello, I'm not able to correctly encode the following string in Python:

  

Algorithm

I have tried the following alternatives:

u'algor\u00edtimo'.encode('utf-8')
'algor\u00edtimo'.decode('utf-8')
u'algor\u00edtimo'.encode('ascii')
u'algor\u00edtimo'.encode('ascii')
    
asked by anonymous 25.02.2015 / 20:51

1 answer

2

Maybe this is what you are looking for:

plaintext = u'algor\u00edtimo'
encodedtext = plaintext.encode('utf-8')
print (encodedtext)

DEMO

To encode a string to ascii you can do:

plaintext = u'algor\u00edtimo'
decodedtext = plaintext.encode('ascii', 'ignore').decode('ascii')
print (decodedtext) # algortimo

The second parameter of the encode function causes probable errors to be ignored in conversion.

To decode a string you can use decode (or unicode ):

plaintext = u'algor\u00edtimo'

encodedtext = plaintext.encode('utf-8')
decodedtext = encodedtext.decode('utf-8')

print (encodedtext)      # algorítimo
print repr(decodedtext)  # u'algor\xedtimo'

DEMO

This applies to Python 2, so there are some differences for 3, see Unicode HOWTO . See also encoding standards .

If you can better specify where you are having difficulties, it is best to solve the problem.

    
25.02.2015 / 21:05