Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Python's bytes type is used for?

Could somebody explain the general purpose of the bytes type in Python 3, or give some examples where it is preferred over other data types?

I see that the advantage of bytearrays over strings is their mutability, but what about bytes? So far, the only situation where I actually needed it was sending and receiving data through sockets; is there something else?

like image 527
pinwheel Avatar asked Oct 09 '19 13:10

pinwheel


People also ask

What is the use of byte data type in Python?

Python bytes() Function It can convert objects into bytes objects, or create empty bytes object of the specified size. The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.

Does Python have byte data type?

Python supports a range of types to store sequences. There are six sequence types: strings, byte sequences (bytes objects), byte arrays (bytearray objects), lists, tuples, and range objects.

How do bytes work in Python?

The bytes type in Python is immutable and stores a sequence of values ranging from 0-255 (8-bits). You can get the value of a single byte by using an index like an array, but the values can not be modified.

What is byte size in Python?

The bytes() function converts an object (such as a list, string, integers, etc.) into an immutable bytes object within the range of 0 to 256. If no object is provided to the bytes() method, it can generate an empty bytes object of a specified size.


1 Answers

Possible duplicate of what is the difference between a string and a byte string

In short, the bytes type is a sequence of bytes that have been encoded and are ready to be stored in memory/disk. There are many types of encodings (utf-8, utf-16, windows-1255), which all handle the bytes differently. The bytes object can be decoded into a str type.

The str type is a sequence of unicode characters. The str needs to be encoded to be stored, but is mutable and an abstraction of the bytes logic.

There is a strong relationship between str and bytes. bytes can be decoded into a str, and strs can be encoded into bytes.

You typically only have to use bytes when you encounter a string in the wild with a unique encoding, or when a library requires it. str , especially in python3, will handle the rest.

More reading here and here

like image 182
Jtcruthers Avatar answered Oct 22 '22 23:10

Jtcruthers