ã½ã¼ã¹ã¯ãã: http://mail.python.org/pipermail/python-dev/2006-December/070238.html
ä¾ãã°ãã¹ãwrapãããªãã¸ã§ã¯ããä½ãã¨ãã«ããã¹ãunicodeã§æ±ãã®ã§ããã°ããã®æåå表ç¾ãunicodeã«ãããã
ãã®ãªãã¸ã§ã¯ãã«æåå表ç¾ãä¸ããã¨ããã¨
class FooPath(object): def __init__(self, path): self.path = path def __str__(self): return "FooPath('%s')" % (self.path,)
self.path ã unicode ã ã¨ããã® __str__() ã®çµæ㯠unicode ã«ãªã£ã¦ãã¾ãã
In [9]: foo = FooPath(u'foobar') In [10]: foo.__str__() Out[10]: u"FooPath('foobar')"
Bazaarã®ã½ã¼ã¹ã§ã __str__() ã unicode ãè¿ãã®ãå«ã£ã¦ã次ã®ããã«ãªã£ã¦ããã
class BarPath(object): def __init__(self, path): assert isinstance(path, unicode) self.path = path def __str__(self): return "BarPath('%s')" % (self.path.encode('utf-8'),) def __unicode__(self): return u"BarPath('%s')" % (self.path,)
ãããããã®æ¹å¼ã§ã¯ä»¥ä¸ã®åé¡ãããã
- print barpath ã¨ããã¨ãã«ãsys.stdout.encodingãç¡è¦ã㦠utf-8 ã使ãããã
- "%s" % (barpath,) ã¨ããã¨ãã«ããã°ã®åºåå ã®ã¨ã³ã³ã¼ãã£ã³ã°ãç¡è¦ã㦠utf-8 ã使ãããã log.warn('%s', barpath) ãåã
å¾è
ã«é¢ãã¦ã¯ u'%s' ã使ãããã«ããã°è¯ããã "%s" % (u"foo") ã®çµæãunicodeã«ãªãã®ã«æ¯ã¹ãã¨çµ±ä¸æãç¡ãã
åè
ã«é¢ãã¦ã¯ããããåé¿æ¹æ³ãç¡ãã
ããã§ã __str__() ã unicode ãè¿ãã¦ããããã®ãã©ãããæ©ã¿ã©ãããªãã ããã©ããä¸è¿°ã®ã¨ããè¯ããããããã ãã次ã®ãããªåé¡ãèµ·ããã®ã§æ°ãã¤ããªãã¨ãããªãã
In [16]: foo = FooPath(u'\u0342') In [19]: "%s" % (foo,) Out[19]: u"FooPath('\u0342')" In [20]: s = str(foo) --------------------------------------------------------------------------- UnicodeEncodeError Traceback (most recent call last)
ãã® UnicodeEncodeError ã§èª°ãæªãã®ãã¨ããã¨ã unicode ãããããªããã®ã«å¯¾ã㦠str() ãå¼ã³åºããå´ãæªãã
str(u"\u0342") ãã¨ã©ã¼ãåºãããããrepr()ã¨éã£ã¦ãstr()ã«é¢ãã¦ã¯ãªãã¸ã§ã¯ãå´ãæåãã責任ãè² ã£ã¦ããªãã
ã§ãããã£ã±ãæ¢åã®ã³ã¼ãã«æãå ããã®ã«ã¯åæ°ãè¦ããªãã