我非常喜欢使用字典格式化字符串.它帮助我阅读我正在使用的字符串格式,并让我利用现有的字典.例如:
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)