带关键字参数的python字符串格式

2024-06-16 11:00:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的情况。在

a={'x':'test'}
b="this is a %(a['x'])s
print b % {'test':'testing'}

期望的结果是

^{pr2}$

但它抛出一个错误“ValueError:incomplete format key”

请给我推荐一个更好的好的。谢谢提前。在


Tags: keytestformatis错误情况thistesting
3条回答

为什么显示错误

在您的代码中(a['x'])只需将键参数转换为“a['x']”

这相当于:

    a={'x':'test'}
    b="this is a %(a['x'])s
    print b % {"a['x']":'testing'}
    "this is a testing"

您可以使用其他答案建议的格式或百分比

需要再创建一个字典。在

>>> a={'x':'test'}
>>> b="this is a %s"
>>> c = {'test':'testing'}
>>> print b % c[a['x']]
this is a testing

你可以在插入字符串之前进行交换。在

c = { 'test' : 'string' }
y = c[a['x']]

然后简单地"mystring %s" % y

如果您不想在使用之前交换值

("{0[%s]}" % a['x']).format(c)

相关问题 更多 >