将字节串格式化为另一个字节串

时间:2016-12-13 08:48:33

标签: python python-3.x byte string-formatting python-3.4

我有一个字节字符串列表,我尝试格式化为另一个字符串,然后我转换为字节,看起来像这样:

byte_string = b'text'
fmt = 'this is the text: %s'
fmt_string = bytes(fmt % byte_string, 'utf-8')

但是如果我打印fmt_string我就会得到这个

  

b"这是文字:b' text'"

我知道在python3.5中我可以这样做:

b'this is the text: %s' % b'text'

并收到:

  

b'这是文字:文字'

有没有办法用python3.4做同样的事情?

1 个答案:

答案 0 :(得分:2)

您无法在Python 3.4或更低版本的bytes对象上使用格式。您可以选择升级到3.5或更高版本,或者不使用字节格式化。

在Python 3.5及更高版本中,您需要将fmt作为字节对象;您将使用字节文字,并将%运算符应用于

fmt = b'this is the text: %s'
fmt_string = fmt % byte_string

或者,首先对模板进行编码,然后应用值:

fmt = 'this is the text: %s'
fmt_string = bytes(fmt, 'utf-8') % byte_string

如果升级不是一个选项,但您的字节值具有一致的编码,请先解码,然后再次编码:

fmt = 'this is the text: %s'
fmt_string = bytes(fmt % byte_string.decode('utf-8'), 'utf-8')

如果您无法解码bytes值,那么您唯一剩下的选项是连接bytes个对象:

fmt = b'this is the text: '  # no placeholder
fmt_string = fmt + byte_string

当然,如果占位符之后有文本,则需要多个部分。

相关问题