我是使用字典格式化字符串的忠实粉丝.它帮助我阅读我正在使用的字符串格式,以及让我利用现有的字典.例如:
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()
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚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)
Run Code Online (Sandbox Code Playgroud)