1# utf-8 is used here because it is a very common encoding, but you
2# need to use the encoding your data is actually in.
3bytes = b'abcde'
4bytes.decode("utf-8")
5'abcde'
1>>> (1024).to_bytes(2, byteorder='big')
2b'\x04\x00'
3>>> (1024).to_bytes(10, byteorder='big')
4b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
5>>> (-1024).to_bytes(10, byteorder='big', signed=True)
6b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
7>>> x = 1000
8>>> x.to_bytes((x.bit_length() + 7) // 8, byteorder='little')
9b'\xe8\x03'
10
1>>> ''.join(['A', 'B', 'C'])
2'ABC'
3>>> ''.join({'A': 0, 'B': 0, 'C': 0}) # note that dicts are unordered
4'ACB'
5>>> '-'.join(['A', 'B', 'C']) # '-' string is the seprator
6'A-B-C'
7
1def bit_length(self):
2 s = bin(self) # binary representation: bin(-37) --> '-0b100101'
3 s = s.lstrip('-0b') # remove leading zeros and minus sign
4 return len(s) # len('100101') --> 6
5