Python Forum

Full Version: appending to a bytearray
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
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:
Output:
>>> ab=bytearray(b'foobar') >>> ab.append(120) >>> ab bytearray(b'foobarx') >>> ab.append(121,122) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: append() takes exactly one argument (2 given) >>> ab.append([121,122]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'list' object cannot be interpreted as an integer >>> ab.append(121) >>> ab.append(122) >>> ab bytearray(b'foobarxyz') >>>
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)
Output:
bytearray(b'bytes and more bytes')
thank you. i was thinking of a string, such as bytearray, as "one" value, so i never thought of .extend().
another way to extend a bytearray is with a slice:
Output:
lt1a/forums/3 /home/forums 13> py Python 3.8.10 (default, Nov 14 2022, 12:59:47) [GCC 9.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> x = bytearray(b"bytes") >>> x[len(x):]=b" and more bytes" >>> print(x) bytearray(b'bytes and more bytes') >>>
an even uglier way:
Output:
>>> print(x) bytearray(b'bytes and more bytes') >>> x[:]=x+b'and even more bytes' >>> print(x) bytearray(b'bytes and more bytesand even more bytes') >>>
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.
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().
(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()?
Output:
>>> help(bytearray.extend) Help on method_descriptor: extend(self, iterable_of_ints, /) Append all the items from the iterator or sequence to the end of the bytearray. iterable_of_ints The iterable of items to append.
what did i do wrong with this? how do i fix it?
Output:
>>> >>> b=bytearray() >>> for x in bytearray(b'abc'): ... b.extend(x) ... Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: can't extend bytearray with int >>>
x is a byte. b'abc' is iterable.. You append(byte) and extend(iterable)
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?
Pages: 1 2 3