我想轻松格式化和左对齐一个由浮点加字符串组成的数量(在我的例子中,字符串是度量单位),使用标准 format_spec 语法。
使用下划线表示占用的空间:
>>> print '{:<20.2f} {:s}'.format(1.0, 'kg/hr')
1.00_________________kg/hr
但我真正想要的是一种方便的方式来生成它:
1.00_kg/hr________________
此外,我希望总宽度为 width
format_spec 的组成部分,在本例中为 20(但我想要一个通用的解决方案)。在上面我的错误示例中,结果的最终宽度实际上是 26,因为 20 完全为 float 保留。
我已经搜索过谷歌和SO,但没有找到任何东西。我的后备方案是编写一个 hacky format_spec 解析器来过滤掉浮点格式化部分,应用它使浮点成为字符串,然后重建一个新的 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 可以是标准格式函数中允许的任何内容,并且触发的任何标准错误都应该传播并正确报告浮点部分。
有更聪明的方法吗?
最佳答案
我可能误解了你的意思,但这就是你想要的吗?
>>> print '{:.2f} {:<20}'.format(1.0, 'kg/hr')
1.00_kg/hr_______________
关于python - 打印带有后缀文本的左对齐格式化 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18285765/