I wanted to ask why Python2.7 returns different output when performing these two actions:
lista= ["Hola", "ò.ó"]
print lista
print lista[0],lista[1]
In the first print
it returns:
['Hola', '\xc3\xb2.\xc3\xb3']
And in the second:
Hola ò.ó
My question really is why in the first case it returns '\xc3\xb2.\xc3\xb3' and what should I do so that it returns a list with ['Hello', 'ò.ó'].
I have been with encodes and decodes for a while but there is no way to understand them.
It's not an encoding issue at all, it's a language feature. Broadly explained:
Each object can have two different representations: a representation friendly to the end user, returned by the method
__str__
and a representation intended for the programmer and for debugging processes, implemented in__repr__
. The first is intended to be readable, the second to be explicit and unambiguous.When you do this you actually call the object's
print(lista[0])
method . Instead, when you do this you call the methods of your objects contained in the list.__str__
str
print(list)
__repr__
__repr__
returns a representation of the object that can normally be passed toeval
so that the corresponding object is rebuilt. In other words, it's usually valid Python code.We can see this behavior directly on a string:
We see how
repr
the "internal representation" of the object returns to us.It is intentional behavior. If we have the list it would
["Hola, mundo", "manzanas"]
be confusing to print it using__str__
since we would get:[Hola, mundo, manzanas]
.If you want to print it as you comment, there are several ways. One way to do it, as long as all your list items are strings, is:
We can create our own class to see the above behavior of the
__str__
and methods__repr__
:Let's see how our class behaves: