本文介绍了如何使用python-3.x中的字典格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是使用字典格式化字符串的大粉丝。它可以帮助我阅读我使用的字符串格式,并让我利用现有的字典。例如:
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()
但是,我无法弄清python 3.x语法的做法(或者甚至有可能)。我想做以下
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)
推荐答案
对你有好处
geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))
这篇关于如何使用python-3.x中的字典格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!