【问题标题】:Encode python string directly into bytearray?将python字符串直接编码为bytearray?
【发布时间】:2014-05-21 15:39:44
【问题描述】:

在 Python 中,你可以这样做:

b = bytearray(100)
b[0:3] = 'one'.encode()
b[17:20] = 'two'.encode()

但是,这会创建一个中间 bytes() 对象,从而导致性能欠佳。

有没有类似 encode_into() 的东西可以直接将字符串编码成字节数组?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

我假设你在 python3.x 中工作,否则 b[0:3] = 'one' 工作正常。

对于python3.x,可以使用b字符串前缀:

b[0:3] = b'one'  # parser creates a bytes object, not a string.

【讨论】:

  • 公平点,但这仅适用于字符串文字。我有一个用户指定的字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2016-06-04
  • 2011-06-13
相关资源
最近更新 更多