Jason Zhu
Jason Zhu

Reputation: 2294

Python Strings with Specific WIdth

I have been having a bit of trouble looking up a good explanation on how to do this so pointing me to the right direction would be helpful for the following problem.

I need to have a header printed out in a pretty format along with data, unfortunately what happened is shown below.

DeviceName   KB used   KB quota   KB hard limit   grace   
/media/Stuff        58384   5242880   0   none

In order to do this I built a list for the header.

HEADER=['DeviceName', 'KB USED', . . .]

and the same thing with the other entries that I need to print out. In order to print it out the above I did something like this

print "".join('%s'.rjust(5) %i for i in HEADER)

So this obviously does not work because the rjust just pads spaces to the right of string. Is there a way to print a string such that it takes up exactly a certain width and if the string isn't long enough to fit the width, then just pad it with spaces?

P.S. I am limited to python 2.4 which means I can't use format from python 2.7.

Upvotes: 1

Views: 3002

Answers (4)

jfs
jfs

Reputation: 414199

You could use '%*s':

HEADER = "DeviceName   |KB used|KB quota|KB hard limit| grace".split('|')
data = ["/media/Stuff", 58384, 5242880, 0, None]
print '|'.join(HEADER)
print '|'.join("%*s" % (width, val) for width, val in zip(map(len,HEADER), data))

Output

DeviceName   |KB used|KB quota|KB hard limit| grace
 /media/Stuff|  58384| 5242880|            0|  None

Upvotes: 3

ᅠᅠᅠ
ᅠᅠᅠ

Reputation: 66950

Format the string with a precision:

print ' '.join("%5.5s" % s for s in HEADER)

Or, slice the rjust result:

print ' '.join(s.rjust(5)[:5] for s in HEADER)

Upvotes: 0

Lachezar
Lachezar

Reputation: 6703

You want it the other way around. How about like this:

>>> "%-5s" % 'sss'
'sss  '

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61509

 '%s'.rjust(5)

puts the spaces in, assuming that the literal %s is your string. You're going to be substituting that with another string of unknown length, so you can't justify until after the substitution.

However, you don't want to explicitly .rjust() everything yourself, because that functionality is built into the substitution engine. Just put the field width between the % and the s.

You could build up the format string dynamically by measuring the lengths of strings in the header. Use %% to produce a literal % sign when formatting; thus, '%%%ds' % 10 turns into '%10s', which will produce a field width of 10.

Thus, something like:

format_string = ' '.join('%%%ds' % len(h) for h in HEADER)
print ' '.join(HEADER)
for entry in data: print format_string % entry

Upvotes: 1

Related Questions