How to right-align numeric data?

2019-01-16 16:07发布

问题:

I have some data that I am displaying in 3 column format, of the form:

key: value key: <tab> key: value <tab> key: value.

Here's an example:

p: 1    sl: 10  afy: 4
q: 12   lg: 10  kla: 3
r: 0    kl: 10  klw: 3
s: 67   vw: 9   jes: 3
t: 16   uw: 9   skw: 3
u: 47   ug: 9   mjl: 3
v: 37   mj: 8   lza: 3
w: 119  fv: 8   fxg: 3
x: 16   fl: 8   aew: 3

However, I'd like if the numbers were all right aligned, such as:

a:   1
b:  12
c: 123

How can I do this in Python?

Here is the existing printing code I have:

print(str(chr(i+ord('a'))) + ": " + str(singleArray[i]) + "\t" +
    str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +
    str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))

回答1:

In Python 2.5 use rjust (on strings). Also, try to get used to string formatting in python instead of just concatenating strings. Simple example for rjust and string formatting below:

width = 10
str_number = str(ord('a'))
print 'a%s' % (str_number.rjust(width))


回答2:

In python 2.6+ (and it's the standard method in 3), the "preferred" method for string formatting is to use string.format() (the complete docs for which can be found here). right justification can be done with

"a string {0:>5}".format(foo)

this will use 5 places, however

"a string {0:>{1}}".format(foo, width)

is also valid and will use the value width as passed to .format().



回答3:

Use python string formatting: '%widths' where width is an integer

>>> '%10s' % 10
'        10'
>>> '%10s' % 100000
'    100000'


回答4:

In Python 3.6 you can use Literal String Interpolation, which is less verbose and probably more intuitive to use:

width = 5
number = 123
print (f'{number:>{width}}')

Or just:

number = 123
print (f'{number:>5}')

It reuses much of the str.format() syntax.

I guess/hope this will be the prefered way in the future.



回答5:

If you know aa upper bound for your numbers, you can format with "%<lenght>d" % n. Given all those calculations are done and in a list of (char, num):

mapping = ((chr(i+ord('a')), singleArray[i]), 
           (doubleArray[i][0],doubleArray[i][1]), 
           (tripleArray[i][0],tripleArray[i][1])
           )
for row in mapping:
   print "%s: %3d" % row