How do I 'declare' an empty bytes
variable in Python 3?
I am trying to receive chunks of bytes, and later change that to a utf-8 string.
However, I'm not sure how to declare the initial variable that will hold the entire series of bytes. This variable is called msg
. I can't declare it as None
, because you can't add a bytes
and a NoneType
. I can't declare it as a unicode string, because then I will be trying to add bytes
to a string. Also, as the receiving program evolves it might get me in to a mess with series of bytes that contain only parts of characters. I can't do without a msg
declaration, because then msg
would be referenced before assignment.
The following is the 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 an empty byte string, b''
.
However, concatenating to a string repeatedly involves copying the string many times. A bytearray
, which is mutable, will likely be faster:
msg = bytearray() # New empty byte array
# Append data to the array
msg.extend(b"blah")
msg.extend(b"foo")
To decode the byte array to a string, use msg.decode(encoding='utf-8')
.