我在对象x
上调用一个__repr__()
函数:
val = x.__repr__()
然后我想要把val
字符串存储到SQLite
数据库。问题是,val
应该是unicode格式。
我尝试了以下方法但都没有成功:
val = x.__repr__().encode("utf-8")
和
val = unicode(x.__repr__())
你知道如何解决吗?
我正在使用Python 2.7.2
版本。
对象的表示不应该是Unicode格式。定义__unicode__
方法并将对象传递给unicode()
函数。
repr(x).decode("utf-8")
和 unicode(repr(x), "utf-8")
应该能正常工作。
#!/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
__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)
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™
>>>
__repr__
返回一个Unicode字符串 - 通过安装Python 3。 - Antti Haapala -- Слава Україні