質問

私はaに電話します __repr__() オブジェクト上の関数 x 次のように:

val = x.__repr__()

そして、私は保存したいです val ストリングに SQLite データベース。問題はそれです val Unicodeである必要があります。

私はこれを成功せずに試しました:

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

val = unicode(x.__repr__())

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

私は使用しています Python 2.7.2

役に立ちましたか?

解決

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

他のヒント

オブジェクトの表現はユニコードではありません。定義します __unicode__ メソッドとオブジェクトを渡します unicode().

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関数を使用してRepを使用するたびに、機能しませんでした。以下の変数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™
>>> 

お役に立てれば。

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)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top