pap*_*ane 5 python dictionary tuples string-formatting
此输入:
'%s %(?)s' % {'?': 'a'}
Run Code Online (Sandbox Code Playgroud)
结果如下:
"{'?': 'a'} a"
Run Code Online (Sandbox Code Playgroud)
它将源字符串中的基于元组和基于dict的占位符替换为如果单独使用它们中的任何一个,您将期望的值。
但是,如果反转字符串中占位符的位置,则会出现TypeError:
In [2]: '%(?)s %s' % {'?': 'a'}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-7989b5f88c97> in <module>()
----> 1 '%(?)s %s' % {'?': 'a'}
TypeError: not enough arguments for format
Run Code Online (Sandbox Code Playgroud)
小智 -1
每个 %s 消耗独立 % 符号之后的变量之一。在第一种情况下,有两个变量,即 while 表达式和字典映射。
在第二种情况下,第一个 %s 获取字典映射并使用整个表达式,对其进行评估。这使得第二个 %s 没有匹配的变量。
| 归档时间: |
|
| 查看次数: |
327 次 |
| 最近记录: |