如何使__repr__返回unicode字符串

问题描述:

我称之为__repr__()功能上对象x如下:如何使__repr__返回unicode字符串

val = x.__repr__()

,然后我想val字符串存储到数据库SQLite。问题是 0123'应该是unicode。

我想这没有成功:

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

val = unicode(x.__repr__())

你知道如何纠正呢?

我使用Python 2.7.2

+0

“如何让'__repr__'返回一个unicode字符串” - 通过安装Python 3. – 2016-08-27 09:36:10

repr(x).decode("utf-8")unicode(repr(x), "utf-8")应该工作。

对象的表示不应该是Unicode。定义__unicode__方法并将对象传递给unicode()

+0

好的,但这里的对象不是我的,而是来自一个库。 – xralf 2012-02-17 08:26:45

+1

你能解释为什么一个对象的表示不应该是unicode?谢谢 – Joucks 2013-03-05 10:50:25

+2

@Joucks:见http://stackoverflow.com/questions/3627793/best-output-type-and-encoding-practices-for-repr-functions – 2014-05-01 16:32:59

我遇到了类似的问题,因为我使用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' 

我终于尝试加入来获取文本淘汰之列,而不是

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™ 

现在,它的工作原理!!!!

我尝试了几种不同的方法。每次我用unicode函数使用repr时,它都不起作用。我必须使用join或者像下面的变量e那样声明文本。

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™ 
>>> 

希望这会有所帮助。

在Python2,您可以定义两种方法:

#!/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 

在Python3,只是定义__repr__会确定:

#!/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)