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()
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
但是我不能算出python 3。执行相同的语法(如果可能的话)。我想做以下的事情。
# 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)
6 个解决方案
#1
256
Is this good for you?
这对你有好处吗?
geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))
#2
62
To unpack a dictionary into keyword arguments, use **
. Also,, new-style formatting supports referring to attributes of objects and items of mappings:
要将词典解压到关键字参数中,请使用**。另外,新样式的格式支持引用对象的属性和映射的项:
'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example
#3
28
As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping)
(Python 3.2+):
由于Python 3.0和3.1都是EOL,而且没有人使用它们,所以您可以并且应该使用str.format_map(映射)(Python 3.2+):
Similar to
str.format(**mapping)
, except that mapping is used directly and not copied to adict
. This is useful if for example mapping is adict
subclass.类似于str.format(**映射),除非该映射是直接使用的,而不是复制到命令中。
What this means is that you can use for example a defaultdict
that would supply a default value for keys that are missing:
这意味着您可以使用一个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'
Even if the mapping provided is a dict
, not a subclass, this would probably still be slightly faster.
即使提供的映射是命令,而不是子类,这可能仍然会稍微快一点。
The difference is not big though, given
但差别并不大。
>>> d = dict(foo='x', bar='y', baz='z')
then
然后
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
is about 10 ns (2 %) faster than
大约有10个ns(2%)比?
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and
在我的Python 3.4.3。如果字典中有更多的键,那么差异可能会更大。
Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:
请注意,格式语言要比这个灵活得多;它们可以包含索引表达式、属性访问等,因此可以格式化整个对象,或者其中2个:
>>> 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'
Starting from 3.6 you can use the interpolated strings too:
从3.6开始,你也可以使用插值字符串:
>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.
您只需要记住在嵌套引号内使用其他引用字符。这种方法的另一个优点是,它比调用格式化方法快得多。
#4
14
print("{latitude} {longitude}".format(**geopoint))
#5
5
The Python 2 syntax works in Python 3 as well:
Python 2的语法也适用于Python 3:
>>> class MyClass:
... def __init__(self):
... self.title = 'Title'
...
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>>
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file
#6
4
Since the question is specific to Python 3, here's using the new f-string syntax:
由于这个问题是针对Python 3的,这里使用了新的f-string语法:
>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091
Note the outer single quotes and inner double quotes (you could also do it the other way around).
注意外部单引号和内双引号(您也可以反过来)。
#1
256
Is this good for you?
这对你有好处吗?
geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))
#2
62
To unpack a dictionary into keyword arguments, use **
. Also,, new-style formatting supports referring to attributes of objects and items of mappings:
要将词典解压到关键字参数中,请使用**。另外,新样式的格式支持引用对象的属性和映射的项:
'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example
#3
28
As Python 3.0 and 3.1 are EOL'ed and no one uses them, you can and should use str.format_map(mapping)
(Python 3.2+):
由于Python 3.0和3.1都是EOL,而且没有人使用它们,所以您可以并且应该使用str.format_map(映射)(Python 3.2+):
Similar to
str.format(**mapping)
, except that mapping is used directly and not copied to adict
. This is useful if for example mapping is adict
subclass.类似于str.format(**映射),除非该映射是直接使用的,而不是复制到命令中。
What this means is that you can use for example a defaultdict
that would supply a default value for keys that are missing:
这意味着您可以使用一个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'
Even if the mapping provided is a dict
, not a subclass, this would probably still be slightly faster.
即使提供的映射是命令,而不是子类,这可能仍然会稍微快一点。
The difference is not big though, given
但差别并不大。
>>> d = dict(foo='x', bar='y', baz='z')
then
然后
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)
is about 10 ns (2 %) faster than
大约有10个ns(2%)比?
>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)
on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and
在我的Python 3.4.3。如果字典中有更多的键,那么差异可能会更大。
Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:
请注意,格式语言要比这个灵活得多;它们可以包含索引表达式、属性访问等,因此可以格式化整个对象,或者其中2个:
>>> 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'
Starting from 3.6 you can use the interpolated strings too:
从3.6开始,你也可以使用插值字符串:
>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'
You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.
您只需要记住在嵌套引号内使用其他引用字符。这种方法的另一个优点是,它比调用格式化方法快得多。
#4
14
print("{latitude} {longitude}".format(**geopoint))
#5
5
The Python 2 syntax works in Python 3 as well:
Python 2的语法也适用于Python 3:
>>> class MyClass:
... def __init__(self):
... self.title = 'Title'
...
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>>
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file
#6
4
Since the question is specific to Python 3, here's using the new f-string syntax:
由于这个问题是针对Python 3的,这里使用了新的f-string语法:
>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091
Note the outer single quotes and inner double quotes (you could also do it the other way around).
注意外部单引号和内双引号(您也可以反过来)。