2

In Python, you can do:

b = bytearray(100) b[0:3] = 'one'.encode() b[17:20] = 'two'.encode() 

This, however, creates an intermediate bytes() object, which is leading to suboptimal performance.

Is there anything like encode_into() that will encode a string directly into a bytearray?

1
  • 2
    This is an interesting read; particularly when it gets to struct.pack. Not an answer, but it may help. Commented Apr 8, 2014 at 18:54

1 Answer 1

3

I assume you're working in python3.x, otherwise b[0:3] = 'one' works just fine.

For python3.x, you can use the b string prefix:

b[0:3] = b'one' # parser creates a bytes object, not a string. 
Sign up to request clarification or add additional context in comments.

1 Comment

Fair point, but that only works for string literals. I have a user-specified string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.