Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i modify a byte array?

Tags:

python

arrays

I was reading about bytes and byte array's. I read that byte arrays mutable types! so, when i am trying to modify it i am getting an error saying integer is required Am i missing something here? The following is my code and the error

z=bytearray("hello world","utf-8")
z[0] ="H"

i got the following error

TypeError Traceback (most recent call last) in () ----> 1 z[0]="H"

TypeError: an integer is required

like image 446
InAFlash Avatar asked Oct 21 '25 07:10

InAFlash


1 Answers

As the docs say:

The bytearray type is a mutable sequence of integers in the range 0 <= x < 256.

The reason you can create it with a string as each character is converted to its ASCII integer value. So when assigning 'H' you actually mean to assign 72.

If you want to be able to assign chars, then just pass each one into ord() first.

like image 124
Joe Iddon Avatar answered Oct 22 '25 21:10

Joe Iddon