If a string to be packed is shorter than its format, it'll be followed by '\x00's when unpacked.
One example, in which every length of the string fits the format:
python 代码
- >>> import struct
- >>> fmt = 'c4si5s'
- >>>
- >>> verb = 'have'
- >>> p = struct.pack(fmt, 'i', verb, 2, 'books')
- >>> unp = struct.unpack(fmt, p)
- >>> p
- 'ihave\x00\x00\x00\x02\x00\x00\x00books'
- >>> unp
- ('i', 'have', 2, 'books')
- >>> unp[1] == verb
- True
Here comes another one, in which the verb is changed into 'had':
python 代码
- >>> import struct
- >>> fmt = 'c4si5s'
- >>>
- >>> verb = 'had'
- >>> p = struct.pack(fmt, 'i', verb, 2, 'books')
- >>> unp = struct.unpack(fmt, p)
- >>> p
- 'ihad\x00\x00\x00\x00\x02\x00\x00\x00books'
- >>> unp
- ('i', 'had\x00', 2, 'books')
- >>> unp[1] == verb
- False
- >>>
- >>> unp[1].rstrip('\x00') == verb
- True
So .rstrip('\x00') in Line14 is needed now.