use*_*238 8 python string-formatting
我希望能够访问带有点的字典中的密钥str.format().我怎样才能做到这一点?
例如,没有点的键的格式有效:
>>> "{hello}".format(**{ 'hello' : '2' })
'2'
Run Code Online (Sandbox Code Playgroud)
但是当密钥中有一个点时它不会出现:
>>> "{hello.world}".format(**{ 'hello.world' : '2' })
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'hello'
Run Code Online (Sandbox Code Playgroud)
你不能.该格式字符串语法支持仅整数或有效的Python标识符作为键.从文档:
Run Code Online (Sandbox Code Playgroud)arg_name ::= [identifier | integer]
其中identifier被定义为:
标识符(也称为名称)由以下词法定义描述:
Run Code Online (Sandbox Code Playgroud)identifier ::= (letter|"_") (letter | digit | "_")*
不允许使用点(或分号).
您可以将字典用作二级对象:
"{v[hello.world]}".format(v={ 'hello.world' : '2' })
Run Code Online (Sandbox Code Playgroud)
在这里,我们将字典分配给名称v,然后使用键名称将其编入索引.这些可以是任何字符串,而不仅仅是标识符.
| 归档时间: |
|
| 查看次数: |
1371 次 |
| 最近记录: |