python - 为什么在 Python 中使用基于字典的字符串格式时没有引号?

标签 python python-2.7

我可能有一个愚蠢的问题:

x = {'a':1,'b':2,'c':3}
print "%(a)s" % x   # works fine
print "%('a')s" % x  # failed

有人能告诉我为什么吗?

最佳答案

%(a)sx 中检索现有 a 键的值。

%('a')s 尝试获取不存在的 'a' 键(带引号)的值,这会导致出现错误。

简单代码示例:

>>> x = {"'a'": 'a within quotes', 'a': 'no quotes'}
>>> "%('a')s" % x
'a within quotes'
>>> "%(a)s" % x
'no quotes'

关于python - 为什么在 Python 中使用基于字典的字符串格式时没有引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019341/

相关文章:

python - 我想使用正则表达式检查名称中包含空格的文件并将空格替换为下划线

python - 从 python 中的参数设置参数默认值

python - 在 python 中将输入文件读取为 csv

python - 一次替换字符串中的多个字符

python - 从 NLTK 中的 token 中删除 URL 特征

Python 'requests' 添加参数顺序错误

python - MAMP Python-MySQLdb 问题 : Path to libssl. 1.0.0.dylib 在调用 Python 文件后更改

python - 将 SQLAlchemy 结果作为字典而不是列表返回

python - 文件读/写意外行为

python - Wxpython : Positioning a menu under a toolbar button