如何使用python-3.x中的字典格式化string?
我是使用字典格式化string的忠实粉丝。 它帮助我阅读我正在使用的string格式,并让我利用现有的字典。 例如:
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() 但是,我不能找出python 3.x语法来做同样的事情(或者甚至可能)。 我想做以下事情
 # 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) 
	
这对你有好处吗?
 geopoint = {'latitude':41.123,'longitude':71.091} print('{latitude} {longitude}'.format(**geopoint)) 
 要将字典解压到关键字参数中,请使用** 。 而且,新风格的格式支持引用对象的属性和映射项: 
 '{0[latitude]} {0[longitude]}'.format(geopoint) 'The title is {0.title}s'.format(a) # the a from your first example 
 由于Python 3.0和3.1是EOL,没有人使用它们,你可以并应该使用str.format_map(mapping) (Python 3.2+): 
类似于
str.format(**mapping), 除了直接使用映射而不复制到dict。 如果例如映射是一个dict子类,这是有用的。
 这意味着你可以使用一个defaultdict来为缺less的键提供默认值: 
 >>> 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='foo', bar='bar', baz='baz') 
然后
 >>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d) 
比大约10ns(2%)快
 >>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d) 
在我的Python 3.4.3上。
请注意格式化语言比这个更灵活。 它们可以包含索引expression式,属性访问等等,所以你可以格式化整个对象,或者其中的2个:
 >>> 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' 
 print("{latitude} {longitude}".format(**geopoint)) 
Python 2语法也适用于Python 3:
 >>> class MyClass: ... def __init__(self): ... self.title = 'Title' ... >>> a = MyClass() >>> print('The title is %(title)s' % a.__dict__) The title is Title >>> >>> path = '/path/to/a/file' >>> print('You put your file here: %(path)s' % locals()) You put your file here: /path/to/a/file 
由于这个问题是针对Python 3的,所以使用了新的f-string语法 :
 >>> geopoint = {'latitude':41.123,'longitude':71.091} >>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}') 41.123 71.091 
注意外面的单引号和内部的双引号(你也可以用相反的方法)。