【问题标题】:Python dictionary key formatting for print does not work for numerical strings用于打印的 Python 字典键格式不适用于数字字符串
【发布时间】:2019-05-22 04:37:10
【问题描述】:

我从Python anti-patterns 得知你可以这样做:

person = {
    'first': 'Tobin',
    'age':20
}

print('{first} is {age} years old'.format(**person))
# Output: Tobin is 20 years old

person = {
    'first':'Tobin',
    'last': 'Brown',
    'age':20
}
print('{first} {last} is {age} years old'.format(**person))
# Output: Tobin Brown is 20 years old

但是,当我的字典包含数字键时,它不起作用:

>>> d = {'123': 123}
>>> d
{'123': 123}
>>> print('{123} is 123 value'.format(**d))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range

这适用于 Python 2 和 3。 这是已知的限制吗?

【问题讨论】:

  • 我建议你检查一下这个answer

标签: python dictionary printing


【解决方案1】:

考虑一下,广义上讲,有三种方法可以指示应该将某个外部表达式插入到调用了format 方法的字符串中:

  1. 隐式,按位置

'{}, {}, {}'.format('huey', 'dewey', 'louie') 给出'huey, dewey, louie'

  1. 明确地,按位置

'{2}, {1}, {0}'.format('huey', 'dewey', 'louie') 给出'louie, dewey, huey'

  1. 明确地,按名称

'{first}, {second}, {third}'.format(first='huey', second='dewey', third='louie') 给出'huey, dewey, louie'

回想一下,在 Python 中,关键字参数和变量名不能以数字开头。

这个限制与我们目前的情况有关:如果可以使用这样的关键字参数,我们将无法解决案例 2 和案例 3 之间的歧义{0} 应该引用未命名的附加参数的第一个元素,还是关键字参数0

由于非字符串关键字参数是不可能可能的,因此没有歧义,大括号内的整数始终表示第二种情况。因此,在您的代码中,{123} 实际上是指传递给format 的参数的第 124 个元素-tuple,当然没有这样的元素。

为了完整起见,让我们看一下在 Python 3.6 中引入的 f-strings:

insert_me = 'cake'
print(f'{insert_me}')

输出:

cake

我们不能这样做:

123 = 'cake'  # illegal variable definition
print(f'{123}')

因此,Python 将大括号中的123 解释为一个整数文字,并打印'123'

【讨论】:

  • 这很有意义! print() 查找位置变量的元组只是发现它到达末尾并且无法检索 vars[123]。
  • @kakyo 我意识到我太忙于解释我忘记解决您的具体问题的原因了。是的,就是这样。
【解决方案2】:

您可以如下应用它

   print('{} is 123 value'.format(*d))

它也适用于 Python2 和 Python3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多