2012-02-16 86 views
4

我稱之爲__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

回答

8

repr(x).decode("utf-8")unicode(repr(x), "utf-8")應該工作。

15

對象的表示不應該是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

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™ 

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

我嘗試了幾種不同的方法。每次我用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™ 
>>> 

希望這會有所幫助。

0

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