python字符串格式化固定宽度 [英] python string formatting fixed width

查看:2641
本文介绍了python字符串格式化固定宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把一些浮点数放到一个固定宽度的表中。也就是说,我最多需要12个字符。我想要使​​用至少10个小数(如果有的话);然而,如果10位小数使其占用超过12个字符,则循环。我原来的想法是尝试像这样

 #我只想要12个字符总计

num1 = 0.04154721841
num2 = 10.04154721841

#不是我想要的
print{:< 12.11g}。format((num1))
#想要
打印{:< 12.10f}。format((num1))

#不是我想要的
打印{:< 12.10f}。格式((num2))
#我要
打印{:<12.11g}。格式((num2))

必须有一种方法可以实现这一点,而不必编写一个函数来检查每个数字并根据上述条件进行格式化。我错过了什么?

解决方案

我不确定这是你在找什么,因为它不是完全用格式字符串,但是,当事物变得太长时,您可以使用字符串切片来消除尾随的字符:

$ $ p $ $ $ $ $ $ num1 = 0.04154721841
num2 = 10.04154721841
num3 = 1002.04154721841

print{0:< 12.11g}。format(num1)[:12]
print格式(num2)[:12]
print{0:< 12.11g}。格式(num3)[:12]


$ p $输出:

$ $ $ $ $ $ $ 0.0415472184
10.041547218
1002.0415472

除此之外,我会说你应该只写一个函数,虽然我不是 str.format 东西的专家,所以我可能会遗漏一些东西。


I want to put a bunch of floating point numbers into a fixed-width table. That is, I want a maximum of 12 characters used. I want a minimum of 10 decimals used (if available); however, if 10 decimals makes it take up more than 12 characters, then round. My original thought was to try something like this

# I only want 12 characters used total

num1 = 0.04154721841
num2 = 10.04154721841

# not what I want
print "{:<12.11g}".format((num1))
# what I want
print "{:<12.10f}".format((num1))

# not what I want
print "{:<12.10f}".format((num2))
# what I want
print "{:<12.11g}".format((num2))

There has to be a way to achieve this without writing a function to check every number and give formatting based on the above conditions. What am I missing?

解决方案

I'm not sure this is what you are looking for, since it's not accomplished entirely with the format string, however, you could just use string slicing to lop-off the trailing chars when things get too long:

num1 = 0.04154721841
num2 = 10.04154721841
num3 = 1002.04154721841

print "{0:<12.11g}".format(num1)[:12]
print "{0:<12.11g}".format(num2)[:12]
print "{0:<12.11g}".format(num3)[:12]

outputs:

0.0415472184
10.041547218
1002.0415472

Beyond that, I'd say you should just write a function, though I'm not an expert on the str.format stuff, so I may be missing something.

这篇关于python字符串格式化固定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆