如何使__repr__返回unicode字符串

时间:2012-02-16 20:29:36

标签: python unicode repr

我在对象__repr__()上调用x函数,如下所示:

val = x.__repr__()

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

我试过这个没有成功:

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

val = unicode(x.__repr__())

你知道怎么纠正这个吗?

我正在使用Python 2.7.2

4 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:9)

repr(x).decode("utf-8")unicode(repr(x), "utf-8")应该有效。

答案 2 :(得分:1)

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

现在可行!!!!

我尝试了几种不同的方法。每次我使用unrode函数的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™
>>> 

希望这有帮助。

答案 3 :(得分:1)

在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)