Python bytes() Built in Function
The Python bytes() function returns a bytes object that is an immutable sequence of bytes. The bytes object can be created from various sources, such as strings, integers, iterables, buffers, etc. The bytes object supports methods and operations similar to bytearray objects.
Here are some examples of using bytes() function:
# Example 1: Create a bytes object from a string with encoding
string = "Python is fun"
# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr) # Output: b'Python is fun'
# Example 2: Create a bytes object of given size and initialize with null bytes
size = 10
arr = bytes(size)
print(arr) # Output: b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
# Example 3: Create a bytes object from an iterable of integers
lst = [65, 66, 67]
arr = bytes(lst)
print(arr) # Output: b'ABC'
# Example 4: Access a byte in a bytes object using index
print(arr[0]) # Output: 65
# Example 5: Concatenate two bytes objects using + operator
arr1 = b'Hello'
arr2 = b'World'
arr3 = arr1 + arr2
print(arr3) # Output: b'HelloWorld
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment