8

次のよう__repr__()にオブジェクトの関数を呼び出します。x

val = x.__repr__()

val次に、文字列をSQLiteデータベースに保存します。問題はそれvalがユニコードであるべきだということです。

私はこれを試しましたが成功しませんでした:

val = x.__repr__().encode("utf-8")

val = unicode(x.__repr__())

これを修正する方法を知っていますか?

使っていますPython 2.7.2

4

4 に答える 4

16

オブジェクトの表現はUnicodeであってはなりません。__unicode__メソッドを定義し、オブジェクトをに渡しますunicode()

于 2012-02-16T21:27:59.810 に答える
9

repr(x).decode("utf-8")動作するunicode(repr(x), "utf-8")はずです。

于 2012-02-16T20:32:16.310 に答える
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を使用するたびに、機能しませんでした。以下の変数eのように、joinを使用するか、テキストを宣言する必要があります。

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™
>>> 

お役に立てれば。

于 2013-03-25T18:39:50.273 に答える
1

Python2では、次の2つのメソッドを定義できます。

#!/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)
于 2017-10-30T05:55:08.373 に答える