Input string at a specific offset in memoryview

250 views Asked by At

I would like to modify some values inside a memoryview in Python at a specific offset. Example:

str = "Ys"
#let us assume memoryview[i:i+2].to_bytes() contains b'\x00\x01'
memoryview[i:i+2] = some_function(str)
print(memoryview[i:i+2].to_bytes()) #now contains b'\x59\x73'

How can I do it? I tried everything but I cannot make it work. Thanks in advance.

2

There are 2 answers

0
Maray97 On BEST ANSWER

It is enough to write

bytes(str, 'ascii) #or different encode

I could not understand it because I was trying to put ASCII characters over an ASCII symbol, for instance an 's' over a '\x00' byte which is not printable, then maybe the output sometime can be represented as a byte or as a character, but is still put in the correct way

0
AudioBubble On

Here's an example that may help you:-

mv = memoryview(bytearray(b'abcd'))
mv[1:3] = b'__'
print(mv.tobytes())

The output will be:- b'a__d'

Note that the memoryview object was constructed with a bytearray which is writable. Construction with just b'abcd' will not allow you to do this