我正在处理一个 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/