gpt4 book ai didi

python-2.7 - 字符串格式化 [str.format()],字典键是数字的 str()

转载 作者:太空狗 更新时间:2023-10-29 17:43:34 24 4
gpt4 key购买 nike

这里是 Python 新手。我想知道是否有人可以帮助解决我在 str.format 中使用字典进行字符串插值时遇到的 KeyError .

dictionary = {'key1': 'val1', '1': 'val2'}

string1 = 'Interpolating {0[key1]}'.format(dictionary)
print string1

以上工作正常并产生:

Interpolating val1

但是执行以下操作:

dictionary = {'key1': 'val1', '1': 'val2'}

string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2

结果:

Traceback (most recent call last):
File "test.py", line 3, in <module>
string2 = 'Interpolating {0[1]}'.format(dictionary)
KeyError: 1L

所以问题似乎出在将数字键解释为列表索引,恕我直言。 有什么办法可以解决这个问题吗? (即传达这是一个字典键)

如果之前有人问过这个问题,TIA 和道歉(找不到与我的搜索相关的任何内容)。

编辑 1: key 不是之前错误指出的数字。相反,它是数字的字符串表示形式 - 正如 BrenBarn 所指出的那样.

最佳答案

没有。根据the documentation :

Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.

所以你不能使用由数字组成的字符串作为格式字符串中的字典键。

请注意,您的键不是数字,也不会尝试将其用作列表索引。您的 key 是一个恰好包含数字字符的字符串。它试图做的是使用数字 1(不是字符串“1”)作为字典键。如果您使用数字 1 作为字典键(即,使您的字典 {'key1': 'val1', 1: 'val2'}),它将起作用。

关于python-2.7 - 字符串格式化 [str.format()],字典键是数字的 str(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11130790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com