给定一个字节对象和一个索引,我想从索引和下一个空值(\ x00)之间的字节中读取一个字符串。例如:从字节中获取一个字符串直到空
bstr=b'abc\x00defg'
addr_to_str(bstr,0) # 'abc'
addr_to_str(bstr,1) # 'bc'
addr_to_str(bstr,4) # 'defg'
我可以做到以下几点:
def addr_to_str(bstr,i):
return bstr[i:].split(b'\x00')[0].decode('utf-8')
由于bytes对象是非常大的,我想的addr_to_str
一个有效的版本。我是Python新手,不知道解释器如何处理split()
调用,我只想访问第一个拆分结果。或者需要.decode()
?
问题:有没有更好的和pythonic的方式来做addr_to_str()
?
['bytes.split()'](https://docs.python.org/3/library/stdtypes.html?highlight=split#bytes.split)有一个可选的'maxsplit'参数...或者你可以使用['bytes.partition()'](https://docs.python.org/3/library/stdtypes.html?highlight=partition#bytes.partition),它只做一个。 – martineau 2015-02-23 21:18:06