Python 3 如何“声明”一个空的`bytes` 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16678363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3 How do I 'declare' an empty `bytes` variable
提问by tsteemers
How do I 'declare' an empty bytesvariable in Python 3?
如何bytes在 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 bytesand a NoneType. I can't declare it as a unicode string, because then I will be trying to add bytesto 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 msgdeclaration, because then msgwould be referenced before assignment.
The following is the code in question
我正在尝试接收大块的字节,然后将其更改为 utf-8 字符串。但是,我不确定如何声明将保存整个字节系列的初始变量。这个变量被称为msg。我不能将其声明为None,因为您不能添加 abytes和 a NoneType。我不能将其声明为 unicode 字符串,因为那样我将尝试添加bytes到字符串中。此外,随着接收程序的发展,它可能会让我陷入只包含部分字符的一系列字节中。我不能没有msg声明,因为 thenmsg会在赋值之前被引用。以下是有问题的代码
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))
采纳答案by Mechanical snail
Just use an empty byte string, b''.
只需使用一个空字节字符串,b''.
However, concatenating to a string repeatedly involves copying the string many times. A bytearray, which is mutable, will likely be faster:
但是,重复连接到一个字符串涉及多次复制该字符串。Abytearray是可变的,可能会更快:
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').
要将字节数组解码为字符串,请使用msg.decode(encoding='utf-8').
回答by PSS
As per documentation:
根据文档:
Blockquote socket.recv(bufsize[, flags]) Receive data from the socket. The return value is a stringrepresenting the data received. Blockquote So, I think msg="" should work just fine:
Blockquote socket.recv(bufsize[, flags]) 从套接字接收数据。返回值是一个表示接收到的数据的字符串。Blockquote 所以,我认为 msg="" 应该可以正常工作:
>>> msg = ""
>>> msg
''
>>> len(msg)
0
>>>
回答by Dr. Sahib
Use msg = bytes('', encoding = 'your encoding here').
使用msg = bytes('', encoding = 'your encoding here').
Encase you want to go with the default encoding, simply use msg = b'', but this will garbage the whole buffer if its not in the same encoding
如果您想使用默认编码,只需使用msg = b'',但是如果它不是相同的编码,这将垃圾整个缓冲区

