User Tools

Site Tools


unicode_y_python

Unicode y Python

Una excelente presentación que arroja luz sobre algunos “enigmas”: Unicode In Python, Completely Demystified (Kumar McMillan, PyCon 2008, Chicago)

Otros documentos relevantes: http://del.icio.us/fgomez/unicode+python.

>>> # Definimos un string unicode:
>>> yo = u'Fernando G\u00f3mez'  # U+00F3 = ó = Latin Small Letter O with acute
>>> yo
u'Fernando G\xf3mez'
>>> yo == u'Fernando G\N{Latin Small Letter O with acute}mez'
True
 
>>> # En efecto, se trata de un objeto de tipo unicode:
>>> type(yo)
<type 'unicode'>
 
>>> # Ahora lo convertimos a string de bytes, aplicando dos encodings:
>>> yo_latin1 = yo.encode('latin-1')
>>> yo_latin1
'Fernando G\xf3mez'
>>> yo_utf8 = yo.encode('utf-8')
>>> yo_utf8
'Fernando G\xc3\xb3mez'
 
>>> # Verificamos que se trata de otro tipo de objetos:
>>> type(yo_latin1)
<type 'str'>
>>> type(yo_utf8)
<type 'str'>
 
>>> # Y volvemos hacia atrás:
>>> yo_latin1.decode('latin-1') == yo_utf8.decode('utf-8') == yo
True
unicode_y_python.txt · Last modified: 30/04/2009 00:00 (external edit)