Cómo hacer __repr__ para devolver una cadena Unicode
Pregunta
Yo llamo a un __repr__()
función en el objeto x
como sigue:
val = x.__repr__()
Y luego quiero almacenar val
hacer una cuerda a SQLite
base de datos. El problema es ese val
debe ser unicode.
Intenté esto sin éxito:
val = x.__repr__().encode("utf-8")
y
val = unicode(x.__repr__())
¿Sabes cómo corregir esto?
Estoy usando Python 2.7.2
Solución
repr(x).decode("utf-8")
y unicode(repr(x), "utf-8")
Deberia trabajar.
Otros consejos
La representación de un objeto no debe ser unicode. Definir el __unicode__
método y pasar el objeto a unicode()
.
Estaba teniendo un problema similar, porque estaba sacando el texto de una lista usando 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'
Finalmente intenté unirme a sacar el texto de la lista.
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™
¡¡¡¡Ahora funciona!!!!
Probé varias maneras diferentes. Cada vez que usé REP con la función Unicode, no funcionó. Tengo que usar unir o declarar el texto como en la variable E a continuación.
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™
>>>
Espero que esto ayude.
En Python2, puedes definir dos métodos:
#!/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
En python3, solo defina __repr__
estará bien:
#!/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)