使用字典解包格式化字符串 (Python 3.9)
Format a string using dictionary unpacking (Python 3.9)
mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}
result = mystr.format(**mydict)
其中加注:
IndexError: Replacement index 1 out of range for positional args tuple
我可以做到以下几点:
mystr = '{name} {number}'
mydict = {'number': '5', 'name': 'ZIDANE'}
result = mystr.format(**mydict)
这给了我结果:ZIDANE 5
我怎样才能达到同样的效果:
mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}
问题是键是整数的(字符串),这与用 list
替换的表示法 冲突 (第二个示例)。这是由于(我猜)__getitem__
、here 一些更多示例的实施。
这里有 non-integer 个键:
mydict = {'0.': '5', '1.': 'ZIDANE'} # with float-keys it works
print('{d[0.]} {d[1.]}'.format(d=mydict))
这里有一个列表的例子
mylst = ['5', 'ZIDANE']
print('{l[0]} {l[1]}'.format(l=mylst))
字典遇到类似的side-effect:
print(dict(a=5, b='ZIDANE'))
#{'a': 5, 'b': 'ZIDANE'}
print(dict(1=5, 2='ZIDANE'))
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
print(dict('1'=5, '2'='ZIDANE'))
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}
result = mystr.format(**mydict)
其中加注:
IndexError: Replacement index 1 out of range for positional args tuple
我可以做到以下几点:
mystr = '{name} {number}'
mydict = {'number': '5', 'name': 'ZIDANE'}
result = mystr.format(**mydict)
这给了我结果:ZIDANE 5
我怎样才能达到同样的效果:
mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}
问题是键是整数的(字符串),这与用 list
替换的表示法 冲突 (第二个示例)。这是由于(我猜)__getitem__
、here 一些更多示例的实施。
这里有 non-integer 个键:
mydict = {'0.': '5', '1.': 'ZIDANE'} # with float-keys it works
print('{d[0.]} {d[1.]}'.format(d=mydict))
这里有一个列表的例子
mylst = ['5', 'ZIDANE']
print('{l[0]} {l[1]}'.format(l=mylst))
字典遇到类似的side-effect:
print(dict(a=5, b='ZIDANE'))
#{'a': 5, 'b': 'ZIDANE'}
print(dict(1=5, 2='ZIDANE'))
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
print(dict('1'=5, '2'='ZIDANE'))
#SyntaxError: expression cannot contain assignment, perhaps you meant "=="?