使用vars或__dict__的Python固定宽度字符串格式



我正在一个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个属性,如果这是可行的,那将使生活变得更容易。

谢谢。

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

From 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

可以这样做:

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)

最新更新