[英]Python fixed width string format using vars or __dict__
我正在研究一個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_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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.