简体   繁体   中英

Iron python: How to append string to bytearray

I have a bytearray to which I have to add a number as a four character string. ig 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

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'))
arr.extend(bytes(format(id,"04x")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM