Python3では、すべての文字列はUnicode文字のシーケンスである。Python3で文字列を生成するときは文字をシングルクォートで囲みます。
1 2 3 4 5 6 7 8 9 |
$ pythn3 Python 3.5.2 (default, Sep 10 2016, 08:21:44) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> example_str = 'こんにちは' >>> example_str 'こんにちは' >>> type(example_str) <class 'str'> |
Python3でバイト列を生成するときは先頭にbを記述しバイト列をシングルクォートで囲みます。
1 2 3 4 5 6 7 8 9 |
$ pythn3 Python 3.5.2 (default, Sep 10 2016, 08:21:44) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> example_bytes = b'hello!' >>> example_bytes b'hello!' >>> type(example_bytes) <class 'bytes'> |
文字列をバイト列にしたいときはUTF-8やcp932と呼ばれる文字符号化方式を使います。文字列をバイト列にすることはエンコードと呼ばれる。バイト列を文字列に変換することをデコードと呼ぶ。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$ python3 Python 3.5.2 (default, Sep 10 2016, 08:21:44) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> example_str = 'こんにちは' >>> type(example_str) <class 'str'> >>> len(example_str) 5 >>> example_bytes = example_str.encode('utf-8') >>> example_bytes b'xe3x81x93xe3x82x93xe3x81xabxe3x81xa1xe3x81xaf' >>> type(example_bytes) <class 'bytes'> >>> len(example_bytes) 15 >>> example_str = example_bytes.decode('utf-8') >>> example_str 'こんにちは' |
コメント