[ACCEPTED]-Convert zero-padded bytes to UTF-8 string-strncpy
str.rstrip() to remove the trailing NULs:
>>> 'hiya\0\0\0'.rstrip('\0') 'hiya'
replace will only work if the string 10 is padded out to the end of the buffer with 9 nulls. In practice the buffer may not have 8 been initialised to null to begin with so 7 you might get something like
If you know 6 categorically 100% that the C code starts 5 with a null initialised buffer and never 4 never re-uses it, then you might find
rstrip to 3 be simpler, otherwise I'd go for the slightly 2 messier but much safer:
>>> b'hiya\0x\0'.split(b'\0',1) b'hiya'
which treats the 1 first null as a terminator.
Unlike the split/partition-solution this 2 does not copy several strings and might 1 be faster for long bytearrays.
data = b'hiya\0\0\0' i = data.find(b'\x00') if i == -1: return data return data[:i]
More Related questions