Python 3 How do I 'declare' an empty `bytes` variable -
how 'declare' empty bytes
variable in python 3?
i trying receive chunks of bytes, , later change utf-8 string. however, i'm not sure how declare initial variable hold entire series of bytes. variable called msg
. can't declare none
, because can't add bytes
, nonetype
. can't declare unicode string, because trying add bytes
string. also, receiving program evolves might me in mess series of bytes contain parts of characters. can't without msg
declaration, because msg
referenced before assignment. following code in question
def handleclient(conn, addr): print('connection from:', addr) msg = ? while 1: chunk = conn.recv(1024) if not chunk: break msg = msg + chunk msg = str(msg, 'utf-8') conn.close() print('received:', unpack(msg))
just use empty byte string, b''
.
however, concatenating string repeatedly involves copying string many times. bytearray
, mutable, faster:
msg = bytearray() # new empty byte array # append data array msg.extend(b"blah") msg.extend(b"foo")
to decode byte array string, use msg.decode(encoding='utf-8')
.
Comments
Post a Comment