如何在python-3.x中使用字典格式化字符串?
发布于 2021-01-29 14:57:45
我非常喜欢使用字典来格式化字符串。它可以帮助我阅读所使用的字符串格式,也可以利用现有的字典。例如:
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)
关注者
0
被浏览
131