Python固定宽度字符串格式使用vars或__dict __

时间:2016-10-25 16:59:52

标签: python python-2.7

我正在研究一个Python项目,我希望使用一些快捷方式来帮助格式化字符串中的类数据。更具体地说,我希望能够使用与'{a}{b}{c}'.format(**vars(self), [strlen, strlen, strlen])类似的东西,并指定显示的每个属性的字符串长度。例如:

class Dummy(object):
    def __init__(self):
        self.value1 = 'A VALUE'
        self.value2 = 'ANOTHER VALUE'
        self.value3 = 'THIRD VALUE'

    def to_s(self):
        # want value1 to be 20 chars
        # value2 to be 8 chars
        # value3 to be 10 chars
        # is something similar to this possible
        return '{value1},{value2},{value3}'.format(**vars(self), [20, 8, 10])


    def to_s2(self):
        # or will I have to reference each explicitly and specify the either padding or slicing?
        return '{},{},{}'.format(self.value1.ljust(20), self.value2[:8], self.value3[:10])

我知道这是一个很长的镜头,但是其中有几个类别有30或40个属性,如果可行,它会让生活变得更加轻松。

感谢。

2 个答案:

答案 0 :(得分:2)

您可以在{}字段中嵌套{}个字段,但只允许嵌套级别。幸运的是,实际上只需要一层嵌套。 :)

来自Format String Syntax

  

format_spec 字段还可以包含嵌套的替换字段   它。这些嵌套的替换字段可能包含字段名称,   转换标志和格式规范,但更深的嵌套不是   允许。 format_spec 中的替换字段已替换   在解释 format_spec 字符串之前。这允许   格式化要动态指定的值。

class Dummy(object):
    def __init__(self):
        self.value1 = 'A VALUE'
        self.value2 = 'ANOTHER VALUE'
        self.value3 = 'THIRD VALUE'

    def __str__(self):
        # want value1 to be 20 chars
        # value2 to be 8 chars
        # value3 to be 10 chars
        return '{value1:{0}},{value2:{1}},{value3:{2}}'.format(*[20, 8, 10], **vars(self))

print(Dummy())

<强>输出

A VALUE             ,ANOTHER VALUE,THIRD VALUE

答案 1 :(得分:1)

这样的事可能有用:

class Dummy(object):
    def __init__(self):
        self.value1 = 'A VALUE'
        self.value2 = 'ANOTHER VALUE'
        self.value3 = 'THIRD VALUE'

    def to_s(self):
        return '{0.value1:<20},{0.value2:8},{0.value3:10}'.format(self)

详细了解https://docs.python.org/2/library/string.html#formatstrings中的格式设置。如果您需要更长的属性列表和更多动态格式,您还可以动态构造格式字符串,例如(另):

    field_formats = [('value1', '<20'),
                     ('value2', '8'),
                     ('value3', '>10'))  # etc.

    def to_s(self):
        fmt = ','.join('{0.%s:%s}' % fld for fld in field_formats)
        return fmt.format(self)
相关问题