Skip to main content
 首页 » 编程设计

python之使用字符串模板格式化时防止类型强制

2024年10月01日76Free-Thinker

>>> b'potato {} potato'.format(u'potato')  # return value matches the template  
'potato potato potato' 
>>> b'potato %s potato' % u'potato'  # return value is coerced 
u'potato potato potato' 

在 str.format 中,模板控制返回类型,但在 str.__mod__ 中,模板被“提升”为 unicode。

  1. 这种行为是否有记录/可靠?
  2. 如何进行百分比样式的替换以使返回类型与模板匹配?

明显的猜测是行不通的:

>>> b'potato %b potato' % u'potato' 
ValueError: unsupported format character 'b' (0x62) at index 8 

我对进行类型检查和/或显式解码/编码调用的解决方案不感兴趣。理想情况下,如果模板变量是 unicode 对象并且无法将其编码为 ascii,我希望模板引发 UnicodeEncodeError。

请您参考如下方法:

这在 String Formatting Operations 部分的开头都有记录在转换表中,具体来说,在该部分的开头说明:

Given format % values ... if format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.

所以这是给定的。

根据我的理解,不涉及 .encode 的解决方案是无法实现的(并且 repring with %r 不是选项)。 str.__mod__ 是一个快速操作,不会为您处理太多事情,.format 具有调用 .encode 的礼貌大胆 为您提供,同时还提供其他好东西(因此它存在的原因)。

另外:如果有人在游荡,它也记录在 PEP 3101 的规范中也就是说,对于 .format,格式字符串的类型将决定结果。