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