8

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

val = x.__repr__()

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

我试过这个没有成功:

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

val = unicode(x.__repr__())

你知道如何纠正这个吗?

我在用着Python 2.7.2

4

4 回答 4

16

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

于 2012-02-16T21:27:59.810 回答
9

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

于 2012-02-16T20:32:16.310 回答
1

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.

于 2013-03-25T18:39:50.273 回答
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)
于 2017-10-30T05:55:08.373 回答