This shows you the differences between two versions of the page.
unicode_y_python [05/04/2009 20:04] fernando movida desde notas |
unicode_y_python [30/04/2009 00:00] |
||
---|---|---|---|
Line 1: | Line 1: | ||
- | ====== Unicode y Python ====== | ||
- | Una excelente presentación que arroja luz sobre algunos "enigmas": [[http://farmdev.com/talks/unicode/|Unicode In Python, Completely Demystified]] (Kumar McMillan, PyCon 2008, Chicago) | ||
- | |||
- | Otros documentos relevantes: [[http://del.icio.us/fgomez/unicode+python]]. | ||
- | |||
- | <code 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 | ||
- | </code> |