4

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

2
  • 7
    Did you mean z[0] = ord('H')? Commented Jun 4, 2018 at 11:37
  • 1
    Oh!, so, i have to give the ascii value? @Norrius Commented Jun 4, 2018 at 11:37

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

7 Comments

so, how would i modify it to have UTF-8 characters?
@Kalyan ASCII is a subset of Unicode encodings, so it is already UTF-8.
@Kalyan Don't use a bytearray! Use a list
@Kalyan It is not a string that it is being modified. It is a bytearray. If you know from C or similar, an array is (normally) a sequence of integers that can be indexed. A string is normally seen in higher-level languages but at the fundamental level, it is an array of integers representing the ASCII characters (a UTF-8 subset). So if you want a string where you can change the characters by index, you would be better of with a list of individual characters e.g: list("hello there") which gives ['h', 'e', 'l', ...] so then you can modify chars by index as lists are mutable.
@Kalyan Oh and when you want to convert that back to a string (for prettier printing etc.) then you can use the join method on an empty string: ''.join(lst).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.