Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]) + "\t" +     str(doubleArray[i][0]) + ": " + str(doubleArray[i][1]) + "\t" +     str(tripleArray[i][0]) + ": " + str(tripleArray[i][1])) 
like image 738
samoz Avatar asked Sep 09 '09 20:09

samoz


People also ask

How do you right align numbers?

Select your data, right-click on it and choose “Format Cells…”. Now, under the Alignment tab, choose “Right (Indent)” for the Horizontal option and put in the indent number. This will normally be 1 or 2. And press “OK” and see the magic!

How do I align numbers to the right in Excel?

To align text or numbers in a cell: Select a cell or range of cells. Click either the Left-Align, Center, or Right-Align buttons on the Standard toolbar. The text or numbers in the cell(s) take on the selected alignment treatment.

How do you right align data?

The alignment keyboard shortcut keys can vary depending on what program is used and the type of computer. However, generally speaking, use Ctrl + L to left align, Ctrl + E to center, Ctrl + R to right align, and Ctrl + J to justify text.

What is the alignment for numeric data?

Alignment Matters Numerical data is read right-to-left; that is, we compare numbers by first looking at their ones digit, then their tens, then their hundreds, and so on. This is also how most people learn arithmetic — start on the right and move left, carrying digits as you go[1].


2 Answers

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

like image 166
Colin Valliant Avatar answered Sep 22 '22 19:09

Colin Valliant


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)) 
like image 22
ChristopheD Avatar answered Sep 22 '22 19:09

ChristopheD