Iron python: How to append string to bytearray

坚强是说给别人听的谎言 提交于 2019-12-11 13:44:48

问题


I have a bytearray to which I have to add a number as a four character string. i.g. 14 should be added as '0014'.

I tried this:

id = 14
arr.append(bytearray(format(id, '04x')))

but it results in: TypeError: unicode argument without an encoding


回答1:


Really you should explicitly specify the encoding when converting to bytes from a string. This answer also works in python 3:

arr.extend(format(id, "04x").encode('ascii'))



回答2:


arr.extend(bytes(format(id,"04x")))


来源:https://stackoverflow.com/questions/22656250/iron-python-how-to-append-string-to-bytearray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!