Pythonでは、文字列を扱う際にstr
とunicode
の2つの型があります。これらの間で変換を行う方法を解説します。
strとは
str
はマルチバイト文字列を扱います。str
を使うと、バイト数を取得したり、バイト毎に処理を行うことができます。
# バイト数を取得
print(len('いろは')) # 9
# バイト毎に処理
for c in 'いろは':
print(c)
unicodeとは
unicode
は文字の単位で文字列を扱います。unicode
を使うと、文字数を取得したり、文字毎に処理を行うことができます。
# 文字数を取得
print(len(u'いろは')) # 3
# 文字毎に処理
for c in u'いろは':
print(c)
unicodeからstrへの変換
unicode.encode()
を使うと、unicode
からstr
に変換できます。
print(u'abc'.encode()) # 'abc'
print(u'いろは'.encode('utf-8')) # '\xe3\x81\x84\xe3\x82\x8d\xe3\x81\xaf'
strからunicodeへの変換
str.decode()
を使うと、str
からunicode
に変換できます。
print('いろは'.decode('utf-8')) # u'\u3044\u308d\u306f'
以上がPythonでunicode
とstr
を変換する基本的な方法です。これらを理解することで、Pythonでの文字列操作がよりスムーズになります。.