![]() |
appending to a bytearray - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: appending to a bytearray (/thread-39567.html) |
appending to a bytearray - Skaperen - Mar-09-2023 i cannot find a way to append a bytes string to a bytearray other than += operator. is that the way it has to be done? bytearray.append() gives an error exception message saying it wants an int. apparently it only takes one at a time:
RE: appending to a bytearray - deanhystad - Mar-09-2023 It is just like a list. append() for adding 1 value, extend() for adding many. x = bytearray(b"bytes") x.extend(b" and more bytes") print(x)
RE: appending to a bytearray - Skaperen - Mar-09-2023 thank you. i was thinking of a string, such as bytearray, as "one" value, so i never thought of .extend(). RE: appending to a bytearray - Skaperen - Mar-09-2023 another way to extend a bytearray is with a slice: an even uglier way: but it's not that much uglier. and i bet these ways can be done with list (and tuples?).edit: yeah, i should'a put a space in there. RE: appending to a bytearray - deanhystad - Mar-09-2023 A bytes object is one object, but so is a list. Both are iterable which is why they can be used as an argument to extend(). RE: appending to a bytearray - Skaperen - Mar-10-2023 (Mar-09-2023, 11:47 PM)deanhystad Wrote: A bytes object is one object, but so is a list. Both are iterable which is why they can be used as an argument to extend().can i use any iterator that produces the expected types (just about anything for a list) as an argument in .extend()? RE: appending to a bytearray - deanhystad - Mar-10-2023
RE: appending to a bytearray - Skaperen - Mar-10-2023 what did i do wrong with this? how do i fix it?
RE: appending to a bytearray - deanhystad - Mar-11-2023 x is a byte. b'abc' is iterable.. You append(byte) and extend(iterable) RE: appending to a bytearray - Skaperen - Mar-12-2023 so, how do i fix b.extend(x) to make it work, such that b ends up with whatever followed in in the loop control?
|