Help us understand the problem. What is going on with this article?

pythonを用いた日本語文字列のデコード

はじめに

たまに「\xE3\x81\xAA\xE3\x82\x93\xE3\x81...」のような文字列を見かけることがあり、読める文字列に変換する方法を知りたくなったので調べてみました。
ほぼ走り書きのメモレベル。

実際のコード

python2の場合

>>> print '\xE3\x81\xAA\xE3\x82\x93\xE3\x81\x8B\xE6\x96\x87\xE5\xAD\x97\xE5\x88\x97'.decode('utf8', 'ignore')
なんか文字列

sjisなら

print '(なんか文字列)'.decode('cp932', 'ignore')

でそれっぽく変換できることが分かりました。
ignoreを入れておくことで途中上手く変換できないコードがあってもスルーされます。
(無視されて当該文字は消える)
ちなみに、ignoreは使えませんが、base64も同じ要領でデコードできます。

python3の場合

>>> b'\xE3\x81\xAA\xE3\x82\x93\xE3\x81\x8B\xE6\x96\x87\xE5\xAD\x97\xE5\x88\x97'.decode('utf8', 'ignore')
'なんか文字列'

で変換できます。

参考

https://docs.python.org/ja/2.7/howto/unicode.html
https://docs.python.org/ja/3/howto/unicode.html

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away