我从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。 这是已知限制吗?
答案 0 :(得分:3)
从广义上讲,可以考虑以下三种方式来指示应将某些外部表达式插入到其format
方法称为的字符串中:
'{}, {}, {}'.format('huey', 'dewey', 'louie')
给出'huey, dewey, louie'
。
'{2}, {1}, {0}'.format('huey', 'dewey', 'louie')
给出'louie, dewey, huey'
。
'{first}, {second}, {third}'.format(first='huey', second='dewey', third='louie')
给出'huey, dewey, louie'
。
回想一下,在Python中,关键字参数和变量名称不能以数字开头。
此限制与我们当前的情况有关:如果可以使用此类关键字参数,我们将无法解决案例2和案例3之间的歧义; {0}
应该引用未命名的其他参数的第一个元素还是关键字参数0
?
由于不可能使用非字符串关键字参数,因此不存在歧义,并且括号内的整数始终表示第二种情况。因此,在您的代码中,{123}
实际上是指传递给tuple
的参数的第124个元素-format
,当然没有这样的元素。
为完整起见,让我们看一下Python 3.6中引入的f字符串:
insert_me = 'cake'
print(f'{insert_me}')
输出:
cake
我们不能这样做:
123 = 'cake' # illegal variable definition
print(f'{123}')
因此,Python将括号中的123
解释为整数文字,并输出'123'
。
答案 1 :(得分:1)
您可以按以下方式应用
print('{} is 123 value'.format(*d))
它同时适用于Python2和Python3