我使用的是struct.pack方法,它接受可变数量的参数。我想把一个字符串转换成字节。如果字符串很短(例如'name'),我可以这样做:
bytes = struct.pack('4c','n','a','m','e')但是当我的字符串有80个字符时该怎么办呢?
我尝试了格式字符串“%s”,而不是struct.pack的“80c”,但结果与上面调用的结果不同。
发布于 2010-12-22 18:42:01
使用"80s",而不仅仅是"s“。输入是单个字符串,而不是一系列字符。即
bytes = struct.pack('4s','name')请注意,如果指定的长度大于输入的长度,则输出将以空值填充。
发布于 2010-12-22 18:40:56
这没有多大意义。在python2.x中,字符串已经是字节了;所以你可以这样做:
my_string = 'I am some big string'
my_bytes = my_string在python 3中,字符串默认是unicode对象。要获取字节,您必须对字符串进行编码。
my_bytes = my_string.encode('utf-8')如果你真的想使用struct.pack,你可以使用* syntax作为described in the tutorial
my_bytes = struct.pack('20c', *my_string)或
my_bytes = struct.pack('20s', my_string)https://stackoverflow.com/questions/4508272
复制相似问题