python struct 45s_python32版本,struct.error: argument for 's' must be a bytes object - 小众知识...

@for ever 2012-06-25

在python32版本下面,下面的代码:

[python] view plaincopy

msg = pack(">H%ds" % len(reason), code, reason)

执行后出现如下的错误:

[plain] view plaincopy

struct.error: argument for 's' must be a bytes object

做如下修改,错误解决:

[python] view plaincopy

msg = pack(">H%ds" % len(reason), code, reason.encode('utf-8'))

[python] view plaincopy

关于struct.pack函数,参数个数是无限的。第一个参数定义打包格式,

剩余的所有参数都是要打包的内容。

第一个格式参数具体写法如下:

Format c Type

Python Note

x pad byte no value

c char string of length 1

b signedchar integer

B unsignedchar

integer

? _Bool bool (1)

h short integer

H unsignedshort

integer

i int integer

I unsignedint

integer or long

l long integer

L unsignedlong

long

q longlong long (2)

Q unsignedlonglong

long (2)

f float float

d double float

s char[] string

p char[] string

P void* long

此外,还包含相应的大/小端设置(如果忽略该设置,默认

@ native native

= native standard

< little-endian

standard

> big-endian standard

! network (= big-endian)

standard

@forandever 2012-6-25

3

down vote

favorite

I am attempting to execute the code:

values = (1, 'ab', 2.7)

s.struct.Struct('I 2s f')

packed = s.pack(*values)

But I keep getting the error:

Traceback (most recent call last):

File "", line 1, in

struct.error: argument for 's' must be a bytes object

Why? How do I fix this?

With Python 3, 'ab' isn't a bytes object, what was called a str on Python 2, it's unicode. You need to use:

values = (1, b'ab', 2.7)

which tells Python that 'ab' is a byte literal. See PEP 3112 for more info.

shareimprove this answer

answered Apr 10 '12 at 3:09

agf

55.1k11123145

2

This answer should be marked as THE answer to the question. –  rbaleksandar Sep 29 '13 at 11:33

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值