文字コードと変換処理

詳細な記事:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

必須知識:

  1. Python2ではデフォルトのエンコードはASCII、Python3ではデフォルトはUnicode
  2. UnicodeにはUTF-32(4バイト)、UTF-16(2バイト)、UTF-8(1〜4バイト)があり、現在ではUTF-16が一般的だが、ファイルに保存する際はUTF-8が使われることが多い。これは空間を節約するためである。
  3. Python3ではencode関数は変換しながら文字列をバイト型に変換し、decode関数はバイトを文字列に戻す。

上記の図はPython2に適用される。

-- coding: utf-8 --

author = 'Alex Li'

import sys
print(sys.getdefaultencoding())

msg = "我爱北京天安门"
msg_gb2312 = msg.decode("utf-8").encode("gb2312")
gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk")

print(msg)
print(msg_gb2312)
print(gb2312_to_gbk)

in python2

-- coding:gb2312 -- #このコメントは削除可能

author = 'Alex Li'

import sys
print(sys.getdefaultencoding())

msg = "我爱北京天安门"
#msg_gb2312 = msg.decode("utf-8").encode("gb2312")
msg_gb2312 = msg.encode("gb2312") #デフォルトはUnicodeなのでdecodeは不要
gb2312_to_unicode = msg_gb2312.decode("gb2312")
gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")

print(msg)
print(msg_gb2312)
print(gb2312_to_unicode)
print(gb2312_to_utf8)

in python3

#-----------------------------

# *  coding:gbk  *<br></br>import sys<br></br>print(sys.getdefaultencoding())<br></br><br></br>s ='你好'#unicodo编码<br></br>print(s)<br></br>print(s.encode('gbk'))<br></br>print(s.encode('utf-8'))<br></br>print(s.encode('utf-8').decode('utf-8').encode('gb2312'))<br></br><br></br><br></br>

utf-8
你好
b'\xc4\xe3\xba\xc3'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
b'\xc4\xe3\xba\xc3'

#-*-coding:gb2312 -*-   #このコメントは削除可能
__author__ = 'Alex Li'

import sys
print(sys.getdefaultencoding())


msg = "我爱北京天安门"
#msg_gb2312 = msg.decode("utf-8").encode("gb2312")
msg_gb2312 = msg.encode("gb2312") #デフォルトはUnicodeなのでdecodeは不要
gb2312_to_unicode = msg_gb2312.decode("gb2312")
gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")

print(msg)
print(msg_gb2312)
print(gb2312_to_unicode)
print(gb2312_to_utf8)

タグ: Python 文字コード エンコード デコード UTF-8

6月6日 16:34 投稿