かぴぶろぐ

またかぴったかと思った・・・(´A`;)

Python strとかunicodeとか

encode decode
カテゴリ[ etc ]

pythonで文字列・エンコード/デコード周りをいじってると、よくぶち当たる以下のエラー。


Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)

後、strとu"文字列"のunicode文字列では、マルチバイト含むと、len()で数えた時の結果が違う。
なので、「何文字目まで」みたいな事をやりたい時はunicodeにして切る。

とりあえず、ちゃんと理解していこう・・。
str文字列「1ニ34ご」でテストしてみる。

>>> s = "1ニ34ご"
>>> s
'1\xef\xbe\x86\xef\xbc\x934\xe3\x81\x94'
>>> type(s)
<type 'str'>

>>> print s
1・・シ・縺
>>> len(s)
11
>>> us = s.decode("utf8")
>>> us
u'1\uff86\uff134\u3054'
>>> print us
1ニ34ご
>>> len(us)
5
>>> us[0:3]
u'1\uff86\uff13'
>>> print us[0:3]
1ニ3
>>> ss = us[0:3]
>>> print ss
1ニ3
>>> type(ss)
<type 'unicode'>

>>> ds = ss.encode("utf8")
>>> ds
'1\xef\xbe\x86\xef\xbc\x93'
>>> type(ds)
<type 'str'>

>>>

もともとunicodeで統一されてるフレームワークとかなら、あまり引っかからないが、文字列がstr扱いのフレームワークとかアプリだと、結構つらい思いする。Zopeとか。

http://kapi.jp/kapi_blog/228

2009年05月12日

関連カテゴリ etc

この記事のコメント

この記事にコメントする