简体   繁体   English

Python格式化带双引号和dict的字符串

[英]Python format a string with a double inside quote with a dict

Why formatting with a dict when there is a double quote in the string fails? 当字符串中有双引号时,为什么使用字典格式失败?

'%(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

It works with : 它适用于:

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

You are forgetting the conversion type code: 您忘记了转换类型代码:

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

Note the s strings. 注意s字符串。 The syntax is %(key)conversiontype . 语法为%(key)conversiontype Without a character signalling the conversion type, the parser picks the next character and that's " in your string. 在没有字符表示转换类型的情况下,解析器将选择下一个字符,即字符串中的"

From the 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) ). 映射键(可选),由带括号的字符序列组成(例如(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. 转换类型。

You gave items 1 and 2 (which is optional), but omitted item 7. 您提供了第1项和第2项(可选),但省略了第7项。

Just as you use %s , you should use %(x)s . 就像使用%s ,您也应该使用%(x)s Just as %" is wrong, %(x)" is wrong. 正如%"是错误的, %(x)"是错误的。 You just need to add that little s : 您只需要添加一点s

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

That letter is required for the same reason it is required in normal formatting. 该字母是必需的,其原因与普通格式一样。 You could, as before, also use d , 03d , f , etc. 您可以像以前一样使用d03df等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM