由于 Python 3.0 和 3.1 已经停止更新且无人使用,因此您应该使用str.format_map(mapping)
(Python 3.2+)。
与str.format(**mapping)
类似,但直接使用 mapping 而不是复制到 dict
中。如果 mapping 是 dict
子类,则这很有用。
这意味着您可以例如使用一个 defaultdict
来设置(并返回)缺失键的默认值:
>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'
即使提供的映射是一个字典(
dict
),而不是子类,这可能仍然会略微更快。但由于差异并不大,因此......
>>> d = dict(foo='x', bar='y', baz='z')
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
比...快约10纳秒(2%)。
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
在我的Python 3.4.3上,差异可能会随着字典中键的增加而变大。
请注意,格式语言要比这个灵活得多;它们可以包含索引表达式、属性访问等等,因此您可以对一个整个对象或两个对象进行格式化:
>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'
从3.6版本开始,您也可以使用插值字符串:
>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
您只需要记住在嵌套引号中使用其他引号字符。这种方法的另一个好处是比调用格式化方法快得多。
format_map
。它类似于str.format(**mapping)
,但直接使用mapping
而不是复制到一个dict
。如果mapping
是字典的子类,则这很有用。 - diapirprint(**geopoint)
与print(longitude=71.091, latitude=41.123)
相同。在许多语言中,它被称为splat操作符。在JavaScript中,它被称为spread操作符。在Python中,此操作符没有特定的名称。 - abhisekp