python - 如何在 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()

但是我无法弄清楚 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)

最佳答案

这对你有好处吗?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

https://stackoverflow.com/questions/5952344/

相关文章:

python - 在 Python 中写入 UTF-8 文件

python - 如果我在 Python 脚本运行时修改它会发生什么?

python - super() 失败并出现错误 : TypeError "argument 1 m

python - 如何使 Jupyter Notebook 中的内联图更大?

linux - 从ssh注销后如何使程序继续运行?

python - 如何打印字典的键?

linux - 使用 grep 搜索包含点的字符串

linux - 确定 Linux 二进制文件的直接共享对象依赖关系?

python - 如何使用 open with 语句打开文件

bash - 如何在 Bash 中比较两个点分隔版本格式的字符串?