相关疑难解决方法(0)

如何使用python-3.x中的字典格式化字符串?

我是使用字典格式化字符串的忠实粉丝.它帮助我阅读我正在使用的字符串格式,以及让我利用现有的字典.例如:

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)

python string dictionary python-3.x

196
推荐指数
7
解决办法
15万
查看次数

标签 统计

dictionary ×1

python ×1

python-3.x ×1

string ×1