IronPythonは文字列の扱いが標準のCPythonと違うようなので比較してみました。
おさらい
その前にPython2(CPython2)の文字列について簡単におさらいしておきます。
Python2の文字列にはstrとunicodeの2つがあります。(以下、バイト文字列、ユニコード文字列と表現します)
バイト文字列
>>> str()
''
>>> 'あ'
'\x82\xa0'
ユニコード文字列
>>> unicode()
u''
>>> u'あ'
u'\u3042'
バイト文字列の実体はバイト配列です。len()
の結果はバイト数を返します。
これに対してユニコード文字列は文字数を返します。
>>> isinstance(str(), bytes)
True
>>> len('あ')
2
>>> len(u'あ')
1
ユニコード文字列をバイト文字列に変換するにはencode()
、バイト文字列をユニコード文字列に変換するにはdecode()
を使用します。
>>> u'あ'.encode('shift_jis')
'\x82\xa0'
>>> 'あ'.decode('shift_jis')
u'\u3042'
Python2の文字列についてもっと詳しく知りたい人は以下を参照してください。
Unicode HOWTO — Python 2.7.14 ドキュメント
Python2のstr/unicodeとencode/decode - Qiita
Python2で文字列を処理する際の心掛け - Qiita
比較
それではCPython2.7とIronPython2.7を比較していきます。
インタープリタでの表示結果
実行内容 | CPython2.7 | IronPython2.7 |
---|---|---|
'あ' |
'\x82\xa0' |
u'\u3042' |
u'あ' |
u'\u3042' |
u'\u3042' |
b'あ' |
'\x82\xa0' |
b'B' |
IronPythonの文字列はu
をつけなくてもユニコード文字列になるようです。
type
実行内容 | CPython2.7 | IronPython2.7 |
---|---|---|
type('あ') |
str | str |
type(u'あ') |
unicode | str |
type(b'あ') |
str | bytes |
type(str()) |
str | str |
type(unicode()) |
unicode | str |
type(bytes()) |
str | bytes |
IronPythonの文字列はバイト文字列もユニコード文字列も型としてはstrになるようです。
isinstance()
実行内容 | CPython2.7 | IronPython2.7 |
---|---|---|
isinstance('あ', str) |
True | True |
isinstance('あ', unicode) |
False | True |
isinstance('あ', bytes) |
True | False |
isinstance(u'あ', str) |
False | True |
isinstance(u'あ', unicode) |
True | True |
isinstance(u'あ', bytes) |
False | False |
==
実行内容 | CPython2.7 | IronPython2.7 |
---|---|---|
'あ' == u'あ' |
False | True |
'あ' == b'あ' |
True | False |
u'あ' == b'あ' |
False | False |
encode/decode
実行内容 | CPython2.7 | IronPython2.7 |
---|---|---|
u'あ'.encode('shift_jis') |
'\x82\xa0' |
u'\x82\xa0' |
type(u'あ'.encode('shift_jis')) |
str | str |
u'あ'.encode('shift_jis').decode('shift_jis') |
u'\u3042' |
u'\u3042' |
type(u'あ'.encode('shift_jis').decode('shift_jis')) |
unicode | str |
IronPythonではエンコード/でコードすると文字コードは変わるけど型はそのままのようです。
型が同じなのでバイト文字列とユニコード文字列を判別する方法はありません!
まとめ
- CPython
- 文字列にはバイト文字列を扱うstr型とユニコード文字列を扱うunicode型がある
- unicodeからstrに変換するにはencode()、strからunicodeに変換するにはdecode()を使用する
- str型とbytes型は等価
- IronPython
- 文字列はstr型しかない
- 同じstr型でも内部ではバイト文字列で持っている場合とユニコード文字列で持っている場合がある
- encode()/decode()しても型は変わらない
- strとbytesは別物