问题描述
我非常喜欢使用字典来格式化字符串.它帮助我阅读我正在使用的字符串格式,并让我利用现有的词典.例如:
class MyClass:def __init__(self):self.title = '标题'a = MyClass()打印 '标题是 %(title)s' % a.__dict__path = '/path/to/a/file'打印 '你把你的文件放在这里:%(path)s' % locals()
但是,我无法弄清楚执行相同操作的 python 3.x 语法(或者甚至可能).我想做以下事情
# 失败,KeyError '纬度'geopoint = {'纬度':41.123,'经度':71.091}打印 '{latitude} {longitude}'.format(geopoint)# 成功打印 '{latitude} {longitude}'.format(latitude=41.123,longitude=71.091)
由于 Python 3.0 和 3.1 已经停产并且没有人使用它们,您可以并且应该使用 str.format_map(mapping)
(Python 3.2+):
类似于str.format(**mapping)
,除了直接使用映射而不是复制到dict
.例如,如果映射是 dict
子类,这很有用.
这意味着您可以使用例如 defaultdict
来设置(并返回)丢失的键的默认值:
即使提供的映射是 dict
,而不是子类,这可能仍然会稍微快一些.
虽然差别不大,但
>>>d = dict(foo='x', bar='y', baz='z')然后
>>>'foo 是 {foo},bar 是 {bar},baz 是 {baz}'.format_map(d)比
快约 10 ns (2 %)>>>'foo 是 {foo},bar 是 {bar},baz 是 {baz}'.format(**d)在我的 Python 3.4.3 上.随着字典中的键越多,差异可能会更大,并且
请注意,格式语言比这灵活得多;它们可以包含索引表达式、属性访问等,因此您可以格式化整个对象,或其中的 2 个:
>>>p1 = {'纬度':41.123,'经度':71.091}>>>p2 = {'纬度':56.456,'经度':23.456}>>>'{0[纬度]} {0[经度]} - {1[纬度]} {1[经度]}'.format(p1, p2)'41.123 71.091 - 56.456 23.456'从 3.6 开始,您也可以使用内插字符串:
>>>f'lat:{p1["latitude"]} lng:{p1["longitude"]}''纬度:41.123 lng:71.091'您只需要记住在嵌套引号中使用 other 引号字符.这种方法的另一个优点是它比调用格式化方法要快得多.
I am a big fan of using dictionaries to format strings. It helps me read the string format I am using as well as let me take advantage of existing dictionaries. For example:
class MyClass:
def __init__(self):
self.title = 'Title'
a = MyClass()
print 'The title is %(title)s' % a.__dict__
path = '/path/to/a/file'
print 'You put your file here: %(path)s' % locals()
However I cannot figure out the python 3.x syntax for doing the same (or if that is even possible). I would like to do the following
# Fails, KeyError 'latitude'
geopoint = {'latitude':41.123,'longitude':71.091}
print '{latitude} {longitude}'.format(geopoint)
# Succeeds
print '{latitude} {longitude}'.format(latitude=41.123,longitude=71.091)
As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping)
(Python 3.2+):
What this means is that you can use for example a defaultdict
that would set (and return) a default value for keys that are missing:
>>> 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'
Even if the mapping provided is a dict
, not a subclass, this would probably still be slightly faster.
The difference is not big though, given
>>> d = dict(foo='x', bar='y', baz='z')
then
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
is about 10 ns (2 %) faster than
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and
Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:
>>> 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'
Starting from 3.6 you can use the interpolated strings too:
>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.
这篇关于如何在 python-3.x 中使用字典格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!