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

2024-05-07 06:07:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我非常喜欢使用字典格式化字符串。它可以帮助我阅读我正在使用的字符串格式,还可以让我利用现有的字典。例如:

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()

但是,我无法理解Python3.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)

Tags: path字符串selfformat利用字典title格式
3条回答

这对你有好处吗

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

要将字典解压为关键字参数,请使用**。此外,新样式格式支持引用对象属性和映射项:

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example

由于Python3.0和3.1已经过时,没有人使用它们,因此您可以也应该使用^{}(Python3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

这意味着您可以使用defaultdict来为缺少的键设置(并返回)默认值:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

即使提供的映射是一个dict,而不是一个子类,这可能仍然会稍微快一点

尽管如此,考虑到

>>> d = dict(foo='x', bar='y', baz='z')

然后

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

约为10纳秒(2%),比

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

在我的Python 3.4.3上。当字典中有更多的键时,差异可能会更大,并且


请注意,格式语言比这灵活得多;它们可以包含索引表达式、属性访问等,因此您可以格式化整个对象,或格式化其中的两个:

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

从3.6开始,您也可以使用插值字符串:

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

您只需要记住在嵌套引号中使用其他引号字符。这种方法的另一个优点是它比calling a formatting method.快得多

相关问题 更多 >