Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active August 10, 2022 03:00
Show Gist options
  • Star 36 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devlights/4561968 to your computer and use it in GitHub Desktop.
Save devlights/4561968 to your computer and use it in GitHub Desktop.
Pythonでマルチバイト文字を扱う際に気をつける点。
# vim:fileencoding=utf-8
import codecs
import sys
import types
if __name__ == '__main__':
#
# ターミナルに出力する場合
# 以下のサンプルは、ターミナルに出力する場合は
# うまくいくが、リダイレクトさせてファイルに出力すると
# エラーが発生する.
#
# pythonでのunicode型は文字コードではない.
# str型は文字コードに即したバイト列。
#
# unicode型.decode() ==> str型
# str型.encode() ==> unicode型
#
# unicode型は文字コードではないので、そのまま出力することは
# できない。出力する際は、必ずdecodeを行ってから出力することになる
# ただし、出力先がターミナルの場合、pythonは出力先のエンコードを
# エンコーディングを認識して、decodeしてから出力してくれている。
# (ファイルの場合は何もしないので、そのままunicode型を出力するとエラーとなる)
#
s1 = '日本語文字列(s1)'
s2 = u'日本語文字列(s2)'
print s1 # 文字化け
print s2 # 文字化けしない
print type(s1) # str
print type(s2) # unicode
print s1.decode('utf-8') # str -> unicode に変換. 文字化けしない
print s2.encode('utf-8') # unicode -> str に変換. 文字化けする
print s2.encode('utf-8').decode('utf-8') # unicode -> str -> unicode 文字化けしない
# vim:fileencoding=utf-8
import sys
import types
if __name__ == '__main__':
#
# ファイルに出力する場合
# ファイルに出力する場合は常にstr型で
# 出力しないと文字化けする.
#
# ターミナルの場合、pythonが標準出力のエンコーディングを
# 認識して、unicode型でもうまく出力してくれるが、相手が
# ファイルの場合pythonは、どのエンコーディングを利用すれば
# いいか分からないため。
#
# unicode型.decode() ==> str型
# str型.encode() ==> unicode型
#
s1 = '日本語文字列(s1)'
s2 = u'日本語文字列(s2)'
print s1 # 文字化けしない (str型)
print s2.encode('utf-8') # 文字化けしない (unicode -> str)
print type(s1) # str
print type(s2) # unicode
try:
print s2 # unicodeを出力. UnicodeErrorが発生する
except UnicodeError, e:
print e
try:
print s1.decode('utf-8') # str -> unicodeに変換. UnicodeErrorが発生する
except UnicodeError, e:
print e
print s2.encode('utf-8') # unicode -> str に変換. 文字化けしない
print s2.encode('utf-8').decode('utf-8').encode('utf-8') # str -> unicode -> str 文字化けしない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment