如何使__repr__返回Unicode字符串

7

我在对象x上调用一个__repr__()函数:

val = x.__repr__()

然后我想要把val字符串存储到SQLite数据库。问题是,val应该是unicode格式。

我尝试了以下方法但都没有成功:

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

val = unicode(x.__repr__())

你知道如何解决吗?

我正在使用Python 2.7.2版本。


如何使__repr__返回一个Unicode字符串 - 通过安装Python 3。 - Antti Haapala -- Слава Україні
4个回答

16

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


好的,但是这里的对象不是我的,而是来自一个库。 - xralf
3
你能解释一下为什么对象的表示不应该是Unicode吗?谢谢。 - Joucks
3
@Joucks:请查看https://dev59.com/GnA65IYBdhLWcg3wyh97。 - Aaron Digulla

8

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


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)

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™

现在它可以工作了!!!

我尝试了几种不同的方法。每次我使用repr和unicode函数时,它都无法正常工作。我必须使用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™
>>> 

希望这能有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接