bytearray
có tất cả các phương thức thông thường str
. Bạn có thể thực hiện điều đó dưới dạng một biến thể str
(byte trong Python3)
Trong khi array.array được hướng đến đọc và ghi tệp. 'B' chỉ là một trường hợp đặc biệt cho array.array
Bạn có thể thấy có khá một sự khác biệt nhìn vào dir()
của mỗi
>>> dir(bytearray)
['__add__', '__alloc__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'capitalize', 'center', 'count', 'decode', 'endswith', 'expandtabs', 'extend',
'find', 'fromhex', 'index', 'insert', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
'partition', 'pop', 'remove', 'replace', 'reverse', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip',
'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir(array)
['__add__', '__class__', '__contains__', '__copy__', '__deepcopy__',
'__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__',
'__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__',
'__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append',
'buffer_info', 'byteswap', 'count', 'extend', 'frombytes', 'fromfile',
'fromlist', 'fromstring', 'fromunicode', 'index', 'insert', 'itemsize', 'pop',
'remove', 'reverse', 'tobytes', 'tofile', 'tolist', 'tostring', 'tounicode',
'typecode']
Tôi thực sự nói 'byte' là phiên bản kế thừa của Python 2.x' str', chứ không phải 'bytearray'. –
Điều đó cũng không thực sự chính xác. Python 2.x's 'str' giống như một hỗn hợp của str và byte Python 3.x. – Broseph
@Broseph: Vâng, 'bytes' * là * một kế thừa của 2.x's' str' nhắm mục tiêu "chuỗi không phân biệt byte" dùng trường hợp ... – SamB