【问题标题】:Python string format() function using zero in the syntax to reference dictionaryPython string format() 函数在语法中使用零来引用字典
【发布时间】:2019-04-03 20:00:15
【问题描述】:

我正在阅读Python documentation on fancier output formatting,他们的示例代码令人困惑。在以下代码中:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

0{0[Jack]:d}{0[Sjoerd]:d} 中指的是什么。本教程的解释省略关于这些零的功能的任何提示。 This video tutorial about formatting strings uses the same syntax without explaining it clearly too!

如果我用1 代替0,我会收到错误:

IndexError: tuple index out of range

tuple 与它有什么关系?

取自文档:

如果你有一个很长的格式字符串不想拆分 起来,如果你能引用变量就好了 按名称而不是按位置格式化。这可以通过简单地完成 传递dict并使用方括号'[]'来访问键

【问题讨论】:

  • 0format的第一个参数,即table
  • 请不要在您的问题中编辑答案。这就是答案部分的用途。 =)

标签: python string format


【解决方案1】:

你可以使用:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}'.format(**table))

【讨论】:

  • 是的,这确实是选择关键字以从字典中提取值的方式。非常感谢您的贡献。
【解决方案2】:

0format 参数的索引,在这种情况下为table

它不适用于1,因为只有一个参数,这就是“元组索引超出范围”的意思。

文档确实提到了这个here

括号中的数字可用于表示传入 str.format() 方法的对象的位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多