How to make __repr__ to return a Unicode string

I call the __repr__() function on the x object as follows:

val = x.__repr__()

and then I want to save the val string in a SQLite database. The problem is that val must be unicode.

I tried this without success:

val = x.__repr__().encode("utf-8")

and

val = unicode(x.__repr__())

Do you know how to fix this?

I am using Python 2.7.2

+4
source share
4 answers

repr(x).decode("utf-8") and unicode(repr(x), "utf-8") should work.

+8
source

The representation of an object must not be Unicode. Define the __unicode__ method and pass the unicode() object.

+15
source

I had a similar problem because I was pulling text from a list using the repr function.

 b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol a = repr(b[0]) c = unicode(a, "utf-8") print c >>> 'text\xe2\x84\xa2' 

I finally tried joining to get the text from the list instead

 b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol a = ''.join(b[0]) c = unicode(a, "utf-8") print c >>> text™ 

Now it works !!!!

I tried several different ways. Every time I used the registry using the unicode function, it did not work. I have to use join or declare text, as in variable e below.

 b =['text\xe2\x84\xa2', 'text2'] ## \xe2\x84\xa2 is the TM symbol a = ''.join(b[0]) c = unicode(repr(a), "utf-8") d = repr(a).decode("utf-8") e = "text\xe2\x84\xa2" f = unicode(e, "utf-8") g = unicode(repr(e), "utf-8") h = repr(e).decode("utf-8") i = unicode(a, "utf-8") j = unicode(''.join(e), "utf-8") print c print d print e print f print g print h print i print j *** Remote Interpreter Reinitialized *** >>> 'text\xe2\x84\xa2' 'text\xe2\x84\xa2' textâ„¢ text™ 'text\xe2\x84\xa2' 'text\xe2\x84\xa2' text™ text™ >>> 

Hope this helps.

+1
source

In Python2, you can define two methods:

 #!/usr/bin/env python # coding: utf-8 class Person(object): def __init__(self, name): self.name = name def __unicode__(self): return u"Person info <name={0}>".format(self.name) def __repr__(self): return self.__unicode__().encode('utf-8') if __name__ == '__main__': A = Person(u"皮特") print A 

In Python3, just defining __repr__ will be fine:

 #!/usr/bin/env python # coding: utf-8 class Person(object): def __init__(self, name): self.name = name def __repr__(self): return u"Person info <name={0}>".format(self.name) if __name__ == '__main__': A = Person(u"皮特") print(A) 
0
source

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


All Articles