开发者

python what is this line doing?

I cannot find out what this line is doing: p = struct.pack(">b", x)+p[1:]

can you help me on this? I think it is placing sth at the end of the struct. Is is also possible to place sth in the middle of that struct? Things like: p = struct.pack(">b", x)+p[2:] do开发者_如何学Pythonn't seem to help. Any ideas on this?

Regards


It replaces the first byte of p with a byte representing the value of x. You may or may not have already read this, but here is the documentation for the struct module.

Edit: To replace the second byte, try this:

p = p[:1] + struct.pack(">b", x) + p[2:]


As an alternative to all that string slicing, which is quite inefficient, consider using a bytearray

>>> import struct
>>> p=bytearray('foobar')
>>> p
bytearray(b'foobar')
>>> p[4]=struct.pack(">b", 64)
>>> p
bytearray(b'foob@r')

bytearray has lots of string methods available

>>> dir(p)
['__add__', '__alloc__', '__class__', '__contains__', '__delattr__',
'__delitem__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__',
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__',
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'capitalize', 'center', 'count', 'decode',
'endswith', 'expandtabs', 'extend', 'find', 'fromhex', 'index', 'insert',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'pop', 'remove', 'replace',
'reverse', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']

and is easy to convert back to string when you are done mutating it

>>> str(p)
'foob@r'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜