So machen Sie __Repr__, um die Unicode -Zeichenfolge zurückzugeben
Frage
Ich rufe a __repr__()
Funktion auf Objekt x
folgendermaßen:
val = x.__repr__()
Und dann möchte ich speichern val
Saite an SQLite
Datenbank. Das Problem ist, dass val
sollte Unicode sein.
Ich habe das ohne Erfolg versucht:
val = x.__repr__().encode("utf-8")
und
val = unicode(x.__repr__())
Wissen Sie, wie Sie das korrigieren können?
Ich benutze Python 2.7.2
Lösung
repr(x).decode("utf-8")
und unicode(repr(x), "utf-8")
sollte arbeiten.
Andere Tipps
Die Darstellung eines Objekts sollte nicht ein Unicode sein. Definiere das __unicode__
Methode und übergeben das Objekt an unicode()
.
Ich hatte ein ähnliches Problem, weil ich den Text mit Repr. Aus einer Liste gezogen habe.
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'
Ich habe schließlich versucht, den Text stattdessen aus der Liste zu holen
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™
Jetzt gehts!!!!
Ich habe verschiedene Arten ausprobiert. Jedes Mal, wenn ich Repr mit der Unicode -Funktion verwendete, funktionierte sie nicht. Ich muss Join verwenden oder den Text wie in Variable E unten deklarieren.
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™
>>>
Hoffe das hilft.
In Python2 können Sie zwei Methoden definieren:
#!/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 einfach definieren __repr__
wird in Ordnung sein:
#!/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)