Unicode型とstr型。Pythonさん、勝手にasciiでデコードしないでください。

Pythonは便利ですが、日本語の取り扱いになると突然面倒になる。

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) 

ってなエラーが出る度に日本語圏に生まれたことを呪う…とまではいかないけど、結構いらいらする。

PythonのUnicodeEncodeErrorを知る - HDEラボ
http://lab.hde.co.jp/2008/08/pythonunicodeencodeerror.html
を参考に、忘備録的に記録します。

上記サイト様によれば、最初のエラーは、
str型を文字コード'ascii'でデコードしてunicode型にしようとしたのですが、できませんでした、というエラーです。
また、
encodeは、「Unicode型を特定の文字コードのバイト列(のstr型)にエンコードする」ためのメソッドです。
decodeは、「特定の文字コードのバイト列(のstr型)をデコードしてUnicode型にする」ためのメソッドです。

とのこと。

In [115]: u"あ"
Out[115]: u'\u3042'

In [116]: "あ"
Out[116]: '\xe3\x81\x82'

In [117]: type("あ")
Out[117]: str

In [118]: type(u"あ")
Out[118]: unicode

In [119]: "あ".decode("utf-8")
Out[119]: u'\u3042'

In [120]: u"あ".encode("utf-8")
Out[120]: '\xe3\x81\x82'