python - 强制字典键用作 str.format 的参数说明符

标签 python string format

我有以下字符串插值:

>>> a = {'test1.1': 5}
>>> 'test: {test1.1}'.format(**a)
KeyError: 'test1'

它显然失败了,因为 format 实际上是在尝试访问对象 test1 及其属性 1。有没有办法格式化这个字符串并强制将键值作为字符串? (寻找 Python 2 和 3 解决方案。)

最佳答案

一个小 hack,但它可以解决问题:

In [5]: 'test: {0[test1.1]}'.format(a)
Out[5]: 'test: 5'

[..] 中使用类似字典的索引。 0 是位置索引,a 是第 0 个 参数。如果它是唯一的参数,您可以省略 0

关于python - 强制字典键用作 str.format 的参数说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47138573/

相关文章:

javascript - 将图像从 html canvas 发送到 Flask python 不起作用

python - Numpy:沿指定轴 reshape 数组

python - 使用 pandas 将值从一列替换为另一列?

php - 如何限制 echo 场中的单词

string - assembly GDB 打印字符串

java - 如何在java中初始化一个二维字符串数组

r - 在 R 中导入 excel 文件时日期发生变化

python - 附加 2 个带有行和列子集的 pandas 数据框

python - Golang 相当于使用 F 字符串的 Python 格式化字符串

python - 格式不是字符串文字,也没有格式参数 [-Wformat-security]