铁蟒蛇:如何将字符串追加到字节数组 [英] Iron python: How to append string to bytearray
本文介绍了铁蟒蛇:如何将字符串追加到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个bytearray
,我必须在其中添加一个数字作为四个字符串.例如14应该添加为"0014".
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'.
我尝试过:
id = 14
arr.append(bytearray(format(id, '04x')))
但是它导致:
TypeError: unicode argument without an encoding
推荐答案
当从字符串转换为字节时,确实应该明确指定编码.这个答案也适用于python 3:
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'))
这篇关于铁蟒蛇:如何将字符串追加到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文