I am a bit new to Python, having dabbled in VB.NET, C, and a few other odd languages, so I am finding the approaches used before don’t always apply to Python. In this case, I want to print out a series of integer values into columns and center them in as small amount of code as possible.
With plain strings, this is easy as:
print "%s|%s|%s|%s" \
% (s1.center(w), s2.center(x), s3.center(y), s4.center(z))
Where w through z is some integer value specifying the width of the field that the strings, s1 through s4, should be center in.
Doing the same with numbers when I want to use format specifiers like %0.2x or %4d won’t work because integers don’t have a center function.
Using a more C-oriented approach, I could convert each integer independently:
s1 = str("%0.4x" % (i)).center(w)
s2 = str("%0.2x" % (i)).center(x)
s3 = str("%0.2x" % (i)).center(y)
s4 = str("%0.8x" % (i)).center(z)
print "%s|%s|%s|%s" % (s1, s2, s3, s4)
But that seems to be “unpythonic”, if I am picking up the lingo correctly. What would be a good “pythonic” way to do this? It needs to be something that works with Python 2.4 and 2.7 (I am working in both environments).
Thanks!
Each tuple in
widthsis (padding, width), where each padding associated with a width is used in the string formatting"%0.[padding]d".