高级字符串格式-Python
下面是一个我正在尝试做的快速示例高级字符串格式-Python,python,string,string-formatting,Python,String,String Formatting,下面是一个我正在尝试做的快速示例 box = { 'colour': 'Red', 'dimensions': { 'width': '100px', 'height': '333px', } } print "The box is %(colour)s, wide %(dimensions.width) and high %(dimensions.height)" %box 这在标准库中是可能的吗 如果没有,您会推荐哪些库?您做对了
box = {
'colour': 'Red',
'dimensions': {
'width': '100px',
'height': '333px',
}
}
print "The box is %(colour)s, wide %(dimensions.width) and high %(dimensions.height)" %box
这在标准库中是可能的吗
如果没有,您会推荐哪些库?您做对了,只是您应该使用
{}
而不是%()是的,但不幸的是,只有Python3才应该使用
编辑:
很抱歉,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]
…还有,看看,从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'
下面是我提出的解决方案,虽然str.format
方法可能更简洁,但添加以下函数,然后使用“…format string…”%flatten(box)
以下是一个例子:
>>> 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
以面向对象的方式,您可以将Box作为对象,然后重写\uuu str\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
例如:
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)
或
注意:我把宽度和高度放在一个元组中。示例?python 2.4版本引入了{N}字符串格式,自python 2.7以来,您可以使用{}而不是{0},{1}(位置格式)。在%()以上鼓励使用它,特别是在3.x系列中,因为前者已被弃用print('Hello{},这里是{}。format('world','python'))
另请参见网页:http://docs.python.org/2/library/string.html
是,请使用str.format。您确定吗?我认为python 2.7使用%运算符支持这一点,但我手头没有python系统。如果在字符串中使用
点表示法对您来说非常重要,那么有一种方法可以做到这一点。我知道它是可行的,但是dict解包在这里是如何工作的?为什么width
和height
不需要引号呢?从文档中:表单的表达式“.name”使用getattr()选择命名属性,而表单“[index]”的表达式使用getitem()进行索引查找。
a = Box(height='100px', width='100px', colour='Red')
print(a)
myvar = str(a)