The bytes() function is a built-in function in Python that returns an immutable sequence of bytes. It can be used to create bytes objects from various sources, such as strings, lists, or other bytes objects.
Here are some examples of using bytes():
my_string = "Hello, world!" my_bytes = bytes(my_string, "utf-8") print(my_bytes) |
In this example, we create a string containing the text "Hello, world!", and then use bytes() to create a bytes object from the string, using the "utf-8" encoding. The resulting bytes object contains the ASCII codes for each character in the string.
|
my_list = [72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33]
my_bytes = bytes(my_list)
print(my_bytes)
|
In this example, we create a list of integers representing the ASCII codes for the characters in the string "Hello, world!", and then use bytes() to create a bytes object from the list. The resulting bytes object is equivalent to the one created in the previous example.
|
my_bytes = bytes(b"abcdef")
new_bytes = bytes(my_bytes)
print(new_bytes)
|
In this example, we create a bytes object containing the bytes "abcdef", and then use bytes() to create a new bytes object from the original bytes object. The resulting bytes object is identical to the original bytes object.
The bytes() function is particularly useful when working with binary data, such as file contents or network packets. It provides a simple and efficient way to create and manipulate bytes objects in Python.
It's worth noting that the bytes() function is similar to the bytearray() function, which also returns a sequence of bytes. However, bytearray() returns a mutable byte array, while bytes() returns an immutable bytes object. If you need to modify the bytes in your sequence, you should use bytearray(). If you only need to read the bytes, you can use bytes() for improved performance and memory usage.