python 3中的字节格式

boo*_*ans 1 python formatting

我知道之前有人问过这个问题,但无法让它为我工作。我想要做的是在我的消息中发送一个前缀,如下所示:

msg = pickle.dumps(message)
prefix = b'{:0>5d}'.format(len(msg))
message = prefix + msg
Run Code Online (Sandbox Code Playgroud)

这给了我

AttributeError: 'bytes' object has no attribute 'format'
Run Code Online (Sandbox Code Playgroud)

我尝试使用%和编码进行格式化,但没有一个起作用。

Hen*_*ter 5

你不能formatbytes文字. 您也不能将bytes对象与str对象连接起来。相反,将整个内容放在一起作为 a str,然后将其转换为bytes使用正确的编码。

msg = 'hi there'
prefix = '{:0>5d}'.format(len(msg)) # No b at the front--this is a str
str_message = prefix + msg # still a str
encoded_message = str_message.encode('utf-8') # or whatever encoding

print(encoded_message) # prints: b'00008hi there'
Run Code Online (Sandbox Code Playgroud)

或者,如果您是单线的粉丝:

encoded_message = bytes('{:0>5d}{:1}'.format(len(msg), msg), 'utf-8')
Run Code Online (Sandbox Code Playgroud)

根据您对@Jan-Philip's answer 的评论,您需要指定要传输的字节数?鉴于此,您需要先对消息进行编码,以便您可以正确确定发送消息时的字节数。len函数在调用时产生一个正确的字节数bytes,所以这样的事情应该适用于任意文本:

msg = 'ü' # len(msg) is 1 character
encoded_msg = msg.encode('utf-8') # len(encoded_msg) is 2 bytes
encoded_prefix = '{:0>5d}'.format(len(encoded_msg)).encode('utf-8')
full_message = encoded_prefix + encoded_msg # both are bytes, so we can concat

print(full_message) # prints: b'00002\xc3\xbc'
Run Code Online (Sandbox Code Playgroud)