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

标签 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 个属性,如果可行的话,这会让生活变得容易得多。

谢谢。

最佳答案

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

来自 Format String Syntax :

A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.

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

关于使用 vars 或 __dict__ 的 Python 固定宽度字符串格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40245650/

相关文章:

python - Matplotlibplot_surface 伪面

python - 有人可以解释一下这个词频统计吗?

python - 将 MxN 二维数据点数组重新组织为 N 维数组

python - 如何分别从一个子进程fork一个子进程

list - 如何删除字典列表项

python - 在 Python 2.7.3 中将字段名称分配给 numpy 数组

python - 具有多个不同类型的可选参数的调用函数

Python:向 pandas 数据框添加一列

python - 检查程序列表中的程序是否已安装

python - python 上的简单正则表达式