这是我正在尝试做的一个简单示例
box = {
'colour': 'Red',
'dimensions': {
'width': '100px',
'height': '333px',
}
}
print "The box is %(colour)s, wide %(dimensions.width) and high %(dimensions.height)" %box
标准库可以实现吗?
如果没有,您会推荐哪些图书馆?
答案 0 :(得分:10)
>>> box = {
'colour': 'Red',
'dimensions': {
'width': '100px',
'height': '333px',
}
}
>>> print "The box is {colour}, wide {dimensions[width]} and high {dimensions[height]}".format(**box)
The box is Red, wide 100px and high 333px
答案 1 :(得分:3)
Yes.除非你使用{}
代替%()
,否则你做对了。
答案 2 :(得分:2)
...另外,看看string templates,自2.4以后就已经存在了。
实施例
>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
[...]
ValueError: Invalid placeholder in string: line 1, col 10
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
[...]
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'
答案 3 :(得分:0)
是的,但遗憾的是仅适用于Python3
http://docs.python.org/release/3.0.1/whatsnew/2.6.html#pep-3101
修改强>
抱歉,此功能也移植到python 2中:
>>> import sys
>>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
Platform: linux2
Python version: 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2]
答案 4 :(得分:0)
以面向对象的方式,您可以将Box作为对象,然后覆盖__str__()
和__unicode__()
方法,以在人类可读的字符串中打印宽度和颜色等变量。< / p>
示例:
class Box():
def __init__(self, **kwargs):
self.dimensions = (kwargs.get('width'), kwargs.get('height'),)
self.colour = kwargs.get('colour')
def __str__(self):
return 'The box is {}, wide {}, and {} height'.format(
self.dimensions[0], self.dimensions[1], self.colour)
以下是您如何发起课程:
a = Box(height='100px', width='100px', colour='Red')
这就是你打印它的方式:
print(a)
或
myvar = str(a)
注意:我将宽度和高度放在元组中。
答案 5 :(得分:-1)
这是我提出的解决方案,虽然str.format
方法可能更清晰,但添加以下函数然后使用"...format string..." % flatten(box)
。
def flatten(d, key=None):
r = d.copy()
if key is not None:
r = dict((key+"."+k, v) for k, v in r.iteritems())
for k, v in r.items():
if isinstance(v, dict):
r.update(flatten(v, k))
del r[k]
return r
以下是一个例子:
>>> flatten(box)
{'dimensions.width': '100px', 'colour': 'Red', 'dimensions.height': '333px'}
>>> print "The box is %(colour)s, wide %(dimensions.width)s and high %(dimensions.height)s" % flatten(box)
The box is Red, wide 100px and high 333px