Байты¶
Байтовые строки очень похожи на обычные строки, но с некоторыми отличиями.
Что такое байты? Байт — минимальная единица хранения и обработки цифровой информации. Последовательность байт представляет собой какую-либо информацию (текст, картинку, мелодию. ).
Создание байтовой строки¶
>>> b'bytes' b'bytes' >>> 'Байты'.encode('utf-8') b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b' >>> bytes('bytes', encoding = 'utf-8') b'bytes' >>> bytes([50, 100, 76, 72, 41]) b'2dLH)'
Функция bytes принимает список чисел от 0 до 255 и возвращает байты, получающиеся применением функции chr .
>>> chr(50) '2' >>> chr(100) 'd' >>> chr(76) 'L'
Что делать с байтами? Хотя байтовые строки поддерживают практически все строковые методы, с ними мало что нужно делать. Обычно их надо записать в файл / прочесть из файла и преобразовать во что-либо другое (конечно, если очень хочется, то можно и распечатать). Для преобразования в строку используется метод decode :
>>> b'\xd0\x91\xd0\xb0\xd0\xb9\xd1\x82\xd1\x8b'.decode('utf-8') 'Байты'
Bytearray¶
Bytearray в Python — массив байт. От типа bytes отличается только тем, что является изменяемым.
>>> b = bytearray(b'hello world!') >>> b bytearray(b'hello world!') >>> b[0] 104 >>> b[0] = b'h' Traceback (most recent call last): File "", line 1, in b[0] = b'h' TypeError: an integer is required >>> b[0] = 105 >>> b bytearray(b'iello world!') >>> for i in range(len(b)): . b[i] += i . >>> b bytearray(b'ifnos%>vzun,')
Длина байтовой строки python
Last updated: Feb 18, 2023
Reading time · 3 min
# Table of Contents
# Get the length of a Bytes object in Python
Use the len() function to get the length of a bytes object.
The len() function returns the length (the number of items) of an object and can be passed a sequence (a bytes, string, list, tuple or range) or a collection (a dictionary, set, or frozen set).
Copied!my_bytes = 'hello'.encode('utf-8') print(type(my_bytes)) # 👉️ print(len(my_bytes)) # 👉️ 5
The len() function returns the length (the number of items) of an object.
Here is another example with some special characters.
Copied!my_bytes = 'éé'.encode('utf-8') print(type(my_bytes)) # 👉️ print(len(my_bytes)) # 👉️ 4
The same approach can be used to get the length of a bytearray .
Copied!my_byte_array = bytearray('hello', encoding='utf-8') print(len(my_byte_array)) # 👉️ 5
If you need to get the size of an object, use the sys.getsizeof() method.
Copied!import sys my_bytes = 'hello'.encode('utf-8') print(sys.getsizeof(my_bytes)) # 👉️ 38 print(sys.getsizeof('hello')) # 👉️ 54
The sys.getsizeof method returns the size of an object in bytes.
The object can be any type of object and all built-in objects return correct results.
The getsizeof method only accounts for the direct memory consumption of the object, not the memory consumption of objects it refers to.
The getsizeof() method calls the __sizeof__ method of the object, so it doesn’t handle custom objects that don’t implement it.
# Get the size of a String in Python
If you need to get the size of a string:
- Use the len() function to get the number of characters in the string.
- Use the sys.getsizeof() method to get the size of the string in memory.
- Use the string.encode() method and len() to get the size of the string in bytes.
Copied!import sys string = 'bobby' # ✅ Get the length of the string (number of characters) print(len(string)) # 👉️ 5 # ------------------------------------------ # ✅ get the memory size of the object in bytes print(sys.getsizeof(string)) # 👉️ 54 # ------------------------------------------ # ✅ get size of string in bytes my_bytes = len(string.encode('utf-8')) print(my_bytes) # 👉️ 5 print(len('őŴœ'.encode('utf-8'))) # 👉️ 6
Use the len() function if you need to get the number of characters in a string.
Copied!print(len('ab')) # 👉️ 2 print(len('abc')) # 👉️ 3
The len() function returns the length (the number of items) of an object.
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).