我想轻松格式化和左对齐数量是 float plus string 的复合(在我的情况下,字符串是度量单位),使用标准的format_spec语法。
使用下划线表示消耗的空间:
>>> print '{:<20.2f} {:s}'.format(1.0, 'kg/hr')
1.00_________________kg/hr
但我真正想要的是一种方便的方法:
1.00_kg/hr________________
此外,我希望总宽度为format_spec的width
组件,在本例中为20(但我想要一般解决方案)。在我上面的错误示例中,结果的最终宽度实际上是26,因为20完全是为浮点数保留的。
我已经搜索了Google和SO,但没有找到任何内容。我的后备是编写一个hacky format_spec解析器来过滤掉浮动格式化部分,应用它来使float成为一个字符串,然后重新构建一个新的format_spec,我将其应用于两者的串联。我在一个类中覆盖__format__()
,因此我在调用'{:<20.2f}'.format(my_obj)
时收到format_spec(my_obj
内部包含度量单位,必须在调用__repr__()
时显示)。建议的伪代码:
def __format__(self, format_spec):
float_spec = extract_float_part(format_spec)
# Using the example above, float_spec becomes '.2f'
float_str = string.format(float_value, float_spec)
# Using example, float_str becomes '1.00'
new_format_spec = make_new_format_spec(format_spec)
# Using example, new_format_spec should become '<20s'
output = string.format(' '.join([float_str, unit_str]), new_format_spec)
我真的不想写(也不必维护)extract_float_part()
和make_new_format_spec()
。对于一部分案例(例如,检测和分割期间等)将会很容易,但我担心会有很多角落案例,我将不得不添加大量的样板来处理他们。通常,format_spec可以是标准格式函数中允许的任何内容,并且任何触发的标准错误都应该传播并正确报告浮动部分。
有更聪明的方法吗?
答案 0 :(得分:2)
我可能会误解你,但这是你想要的吗?
>>> print '{:.2f} {:<20}'.format(1.0, 'kg/hr')
1.00_kg/hr_______________
答案 1 :(得分:0)
要解决问题(在上面的评论中,要传递单个字段),您可以尝试:
d = {'value':1.0, 'unit':'kg/hr'}
print '{value:.2f} {unit:<20}'.format(**d)
其中d
可能是您班级的词典成员。
另外,我只是过滤该值以仅接受浮点数。