【问题标题】:Python fixed width string format using vars or __dict__使用 vars 或 __dict__ 的 Python 固定宽度字符串格式
【发布时间】:2016-10-25 16:59:51
【问题描述】:

我正在开发一个 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 个属性,如果可行的话,它会让生活变得更加轻松。

谢谢。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

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

    来自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
    

    【讨论】:

      【解决方案2】:

      这样的事情可能会奏效:

      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)
      

      【讨论】:

        猜你喜欢
        • 2012-01-15
        • 2014-02-13
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        • 1970-01-01
        • 2011-06-15
        相关资源
        最近更新 更多