Skip to content Skip to sidebar Skip to footer

Python String Formatting Fixed Width

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); howe

Solution 1:

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.04154721841print"{0:<12.11g}".format(num1)[:12]
print"{0:<12.11g}".format(num2)[:12]
print"{0:<12.11g}".format(num3)[:12]

outputs:

0.041547218410.0415472181002.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.

Post a Comment for "Python String Formatting Fixed Width"