Hrvoje T
Hrvoje T

Reputation: 3913

Python 2.x - Why are strings contained a list not encoded in output?

When I run this python script:

#!/usr/bin/env python
# coding: windows-1250
lst = ['č']
s = 'č'
print lst
print s

I get this output:

['\xc4\x8d']
č

Why do they look different?

Upvotes: 0

Views: 38

Answers (1)

Thomas Orozco
Thomas Orozco

Reputation: 55207

Theory

print s calls s.__str__(), which returns an encoded string.

However, print lst calls lst.__str__() which in turn calls __repr__() on the members of the list. Unlike __str__, __repr__ which does not return an encoded string.

Practice

You can confirm this with the following test code:

class Test(object):
    def __str__(self):
        return "__str__ was called"

    def __repr__(self):
        return "__repr__ was called"


if __name__ == "__main__":
    print Test()
    print [Test(), Test()]

Which will output:

__str__ was called
[__repr__ was called, __repr__ was called]

Upvotes: 4

Related Questions