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:
- The
'%'
character, which marks the start of the specifier.
- Mapping key (optional), consisting of a parenthesised sequence of characters (for example,
(somename)
).
- Conversion flags (optional), which affect the result of some conversion types.
- 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.
- 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.
- Length modifier (optional).
- Conversion type.
您提供了第 1 项和第 2 项(可选),但省略了第 7 项。
正如您使用 %s
,您应该使用 %(x)s
。正如 %"
是错误的,%(x)"
也是错误的。您只需要添加一点 s
:
'%(x)s"%(y)s' % {'x': 1, 'y':2}
需要该字母的原因与在正常格式中需要的原因相同。您也可以像以前一样使用 d
、03d
、f
等
为什么当字符串中有双引号时用字典格式化会失败?
'%(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:
- The
'%'
character, which marks the start of the specifier.- Mapping key (optional), consisting of a parenthesised sequence of characters (for example,
(somename)
).- Conversion flags (optional), which affect the result of some conversion types.
- 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.- 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.- Length modifier (optional).
- Conversion type.
您提供了第 1 项和第 2 项(可选),但省略了第 7 项。
正如您使用 %s
,您应该使用 %(x)s
。正如 %"
是错误的,%(x)"
也是错误的。您只需要添加一点 s
:
'%(x)s"%(y)s' % {'x': 1, 'y':2}
需要该字母的原因与在正常格式中需要的原因相同。您也可以像以前一样使用 d
、03d
、f
等