Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - How to right-align numeric data?

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]) + "" +
    str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "" +
    str(tripleArray[i][0]) + ": " + str(tripleArray[i][1]))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...