すべての文字列のUnicode化
Python 2.xには、バイト文字列(str)とUnicode文字列(unicode)の2種類の文字列型がありました。バイト文字列には、バイト(通常デフォルトロケールに基づいてPythonで解釈されます)が含まれ、Unicode文字列には当然Unicode文字が含まれます。
>>> s = 'hello' >>> u = u'\u05e9\u05dc\u05d5\u05dd' >>> type(s) <type 'str'> >>> type(u) <type 'unicode'>
strもunicodeも、共通のベースクラス「basestring」から派生しています。
>>> unicode.__bases__ (<type 'basestring'>,) >>> unicode.__base__ <type 'basestring'> >>> str.__bases__ (<type 'basestring'>,)
Python 3.0では、すべての文字列がUnicodeになりました。str型は、Python 2.xのunicode型と同じセマンティクスとなり、別個のunicode型はなくなりました。basestringベースクラスもなくなりました。
>>> s = '\u05e9\u05dc\u05d5\u05dd' >>> type(s) <class 'str'>
Python 2.xのバイト文字列は、bytesとbytearrayの2種類の型になりました。バイト配列には、変更可能と変更不能の両方があります。bytes型では、次のように文字列操作の多数のメソッドがサポートされています。
>>> dir(bytes) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'find', 'fromhex', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
bytearray型にも、変換メソッドextend()、insert()、append()、reverse()、pop()、remove()があります。
どちらも+演算子と*演算子をサポートしており(文字列と同じセマンティクスを使用)、bytearray型では+=と*=もサポートされます。
bytesもbytearrayもエンコードを認識しないのに対し、strオブジェクトにはエンコードが必須なので、エンコードを明示的に指定せずにstrから、またはstrへ変換することはできません。bytesオブジェクトまたはbytearrayオブジェクトをstr()に直接渡すと、repr()の結果が返されます。変換するには、decode()メソッドを使用する必要があります。
>>> a = bytearray(range(48, 58)) >>> a bytearray(b'0123456789') >>> s = str(a) >>> s "bytearray(b'0123456789')" >>> s = a.decode() >>> s '0123456789'
文字列からbytesまたはbytearrayに変換するには、文字列のencode()メソッドを使用するか、bytesオブジェクトまたはbytearrayオブジェクトのコンストラクタにエンコードを渡す必要があります。
>>> s = '1234' >>> s '1234' >>> b = bytes(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: string argument without an encoding >>> b = s.encode() >>> b b'1234' >>> b = bytes(s, 'ascii') >>> b b'1234'
文字列表現も変更になりました。Python 2.xでは、repr()の戻り値はstr型で、ASCIIベースの文字列でした。Python 3.0では、戻り値の型はstrのままですが、Unicode文字列になります。文字列表現のデフォルトのエンコードは、出力デバイスによって決まります。
