Python str () function result is different from __str __ () function result

I am updating a hobby application written in Python 2.7 on Ubuntu 14.04 that stores railway history data in json. I have used it so far to work on UK data.

When I started with the French data, I ran into a problem that puzzled me. I have a class CompaniesCachethat implements __str__(). Inside this implementation, everything uses str. Let's say I instantiate CompaniesCacheand assign a variable companies. When I, in IPython2, give a command print companies, I get an error message:

UnicodeEncodeError: the ascii codec cannot encode the character u '\ xe0' at position 184: the serial number is not in the range (128). "

Well, this is not strange. Testing. str(companies)reproduces the error, as expected. But it companies.__str__()turns out without problems, like print company.__str__(). What is wrong here?

Here is the code for the __str__ method of the CompanyCache object:

class CompaniesCache(object):                                                       
    def __init__(self, railrefdatapath):       
        self.cache = restoreCompanies(railrefdatapath)                                             

    def __getitem__(self, compcode):                                                                                     
        return self.cache[compcode.upper()]                                                                              

    def __str__(self):                                                                
        s = ''                                                                            
        for k in sorted(self.cache.keys()):                                                                              
            s += '\n%s: %s' % (k, self[k].title)                                                                
        return s

This is the code for the CompanyCache object that contains Company objects in the dict cache. The Company object does not implement the __str __ () method.

+4
source share
2 answers

strnot just a cause __str__. Among other things, it checks the type of the return value, it returns to __repr__if __str__not available, and it tries to convert the values unicodetostr using the ASCII codec.

__str__ unicode , ASCII. str bytestring, , , .

unicode __str__. __unicode__, , unicode(your_object), bytestring __str__.

+4

maxpolk , , ,

export LC_ALL='en_US.utf8'

, ,

0

Source: https://habr.com/ru/post/1664939/


All Articles