There are relatively few occasions when you will need to transform an object into bytes. Bytes representation is used for the serialization of objects for persistent storage or transfer. We'll look at this in detail in Chapter 10, Serializing and Saving - JSON, YAML, Pickle, CSV and XML through Chapter 14, Configuration Files and Persistence.
In the most common situation, an application will create a string representation, and the built-in encoding capabilities of the Python IO classes can be used to transform the string into bytes. This works perfectly for almost all situations. The main exception would be when we're defining a new kind of string. In which case, we'd need to define the encoding of that string.
The bytes() function does a variety of things, depending on the arguments:
- bytes(integer): This returns an immutable bytes object...