0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2019-03-12

はじめに

たまに「\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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?