如何在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
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    由于问题是特定于Python 3的,因此这里使用的从Python
    3.6开始可用的新f字符串语法

    >>> geopoint = {'latitude':41.123,'longitude':71.091}
    >>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
    41.123 71.091
    

    注意外部单引号和内部双引号(您也可以采用其他方法)。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看