gpt4 book ai didi

python - 将字节字符串格式化为另一个字节字符串

转载 作者:行者123 更新时间:2023-12-01 03:29:17 26 4
gpt4 key购买 nike

我有一个字节字符串列表,我尝试将其格式化为另一个字符串,然后将其转换为字节,如下所示:

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

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

b"this is the text: b'text'"

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

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

并接收:

b'this is the text: text'

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

最佳答案

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

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

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

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

关于python - 将字节字符串格式化为另一个字节字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41116866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com