Come rendere __repr__ per tornare stringa unicode
Domanda
che io chiamo una funzione __repr__()
sull'oggetto x
come segue:
val = x.__repr__()
e poi voglio memorizzare stringa val
a base di dati SQLite
. Il problema è
che val
dovrebbe essere unicode.
Ho provato questo senza successo:
val = x.__repr__().encode("utf-8")
e
val = unicode(x.__repr__())
Sai come correggere questo?
Sto usando Python 2.7.2
Soluzione
repr(x).decode("utf-8")
e unicode(repr(x), "utf-8")
dovrebbero funzionare.
Altri suggerimenti
La rappresentazione di un oggetto non dovrebbe essere Unicode. Definire il metodo __unicode__
e passare l'oggetto a unicode()
.
ho avuto un problema simile, perché stavo tirando il testo di un elenco utilizzando 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'
Alla fine ho cercato join per ottenere il testo fuori dalla lista, invece
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™
Ora funziona !!!!
Ho provato diversi modi. Ogni volta che ho usato con la funzione repr unicode non ha funzionato. Devo usare aderire o dichiarare il testo come in variabile e qui di seguito.
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™
>>>
Spero che questo aiuti.
In python2, è possibile definire due metodi:
#!/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
In python3, basta definire __repr__
sarà ok:
#!/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)