How to make __repr__ to return unicode string

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

val = x.__repr__()

and then I want to store val string to SQLite database. The problem is that val should be unicode.

I tried this with no success:

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

and

val = unicode(x.__repr__())

Do you know how to correct this?

I'm using Python 2.7.2


ANSWERS:


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


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


I was having a similar problem, because I was pulling the text out of a list using repr.

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 join to get the text out of 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. Each time I used repr with the unicode function it did not work. I have to use join or declare the text like 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.



 MORE:


 ? Doctest fails due to unicode leading u
 ? jsonpickle/json function input utf-8, output unicode?
 ? General Best Practices for encoding using php
 ? Unicode error Ordinal not in range
 ? Read and Write CSV files including unicode with Python 2.7
 ? python encoding utf-8
 ? python encoding utf-8
 ? python encoding utf-8
 ? Writing UTF-8 String to MySQL with Python
 ? What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python