Given a bytes object and an index, I want to read a string from the bytes between the index and the next null(\x00). For example:
bstr=b'abc\x00defg'
addr_to_str(bstr,0) # 'abc'
addr_to_str(bstr,1) # 'bc'
addr_to_str(bstr,4) # 'defg'
I can do the following:
def addr_to_str(bstr,i):
return bstr[i:].split(b'\x00')[0].decode('utf-8')
Since the bytes object is very large, I would like an efficient version of addr_to_str. I am new to Python and not knowing how the interpreter treats the split() call when I only want to access the first split result. Or is the .decode() necessary?
Question: Is there a better and pythonic way to do addr_to_str()?
bytes.split()has an optionalmaxsplitargument...or you could usebytes.partition()which only does one.