Python 3.6+中是否有格式化的字节字符串文字? [英] Is there a formatted byte string literal in Python 3.6+?

查看:74
本文介绍了Python 3.6+中是否有格式化的字节字符串文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找格式化的字节字符串文字.具体来说,等同于

I'm looking for a formatted byte string literal. Specifically, something equivalent to

name = "Hello"
bytes(f"Some format string {name}")

可能类似于fb"Some format string {name}".

这样的东西存在吗?

推荐答案

否. 这个想法在PEP中被明确取消了 :

由于我们不支持bytes.format()的原因,您可能 不能将'f''b'字符串文字结合使用.主要问题 是对象的__format__()方法可能返回Unicode数据 与字节字符串不兼容.

For the same reason that we don't support bytes.format(), you may not combine 'f' with 'b' string literals. The primary problem is that an object's __format__() method may return Unicode data that is not compatible with a bytes string.

二进制f字符串首先需要一种解决方案 bytes.format().这个想法是过去提出的,大多数 最近在 PEP 461 中.通常会讨论这种功能 建议

Binary f-strings would first require a solution for bytes.format(). This idea has been proposed in the past, most recently in PEP 461. The discussions of such a feature usually suggest either

  • 添加诸如__bformat__()的方法,以便对象可以控制如何将其转换为字节,或者

  • adding a method such as __bformat__() so an object can control how it is converted to bytes, or

具有bytes.format()的用途不如str.format()那样通用或可扩展.

having bytes.format() not be as general purpose or extensible as str.format().

如果有这样的功能,将来两者都保留为选项 是理想的.

Both of these remain as options in the future, if such functionality is desired.

这篇关于Python 3.6+中是否有格式化的字节字符串文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆