Python 用字典格式化带有双内引号的字符串

Python format a string with a double inside quote with a dict

为什么当字符串中有双引号时用字典格式化会失败?

'%(x)"%(y)' % {'x': 1, 'y':2}

Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ValueError: unsupported format character '"' (0x22) at index 4

适用于:

'%s"%s' % (1,2)

您忘记了转换类型代码:

>>> '%(x)s"%(y)s' % {'x': 1, 'y':2}
'1"2'

注意 s 字符串。语法是 %(key)conversiontype。如果没有字符表示转换类型,解析器将选择下一个字符,即字符串中的 "

来自string formatting operations documentation:

A conversion specifier contains two or more characters and has the following components, which must occur in this order:

  1. The '%' character, which marks the start of the specifier.
  2. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
  3. Conversion flags (optional), which affect the result of some conversion types.
  4. Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision.
  5. Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision.
  6. Length modifier (optional).
  7. Conversion type.

您提供了第 1 项和第 2 项(可选),但省略了第 7 项。

正如您使用 %s,您应该使用 %(x)s。正如 %" 是错误的,%(x)" 也是错误的。您只需要添加一点 s:

'%(x)s"%(y)s' % {'x': 1, 'y':2}

需要该字母的原因与在正常格式中需要的原因相同。您也可以像以前一样使用 d03df