Print formatting
MRAB
python at mrabarnett.plus.com
Fri Oct 18 13:35:25 EDT 2019
On 2019-10-18 18:03, Jagga Soorma wrote:
> Hello,
>
> I am new to python and trying to write a script that outputs some data
> about users. I was able to write it and dump the data but can't seem
> to align the output in column 2 correctly. Here is what I am trying
> to do:
>
> --
> output:
> user1 data1
> username2 data2
> user3 data3
>
> snip from script:
> print(str(temp_list[0]) + "\t\t" + str(temp_list[1]))
> --
>
> Adding the tabs does not seem to work and I am sure there is a better
> way to do this. Any help would be appreciated.
>
A tab advances the output position to the next tab stop, but there's no
universal standard for where those tab stops are, although they're
commonly at every 8 characters, assuming a monospaced (fixed-width) font.
In your example, if the tabs are at every 8 characters then you'll get:
| | <= The tab positions
user1 data1
username2 data2
user3 data3
"username2" has already passed the first tab, so it advances to the
second tab, causing the misalignment.
The simplest solution, if you're using a monospaced font, is to use
spaces instead. Find the width of the first column (the longest entry in
the first column is 9 characters) and then pad all of the first entries
with spaces to that width (use string formatting or the .just method)
when outputting each line.
More information about the Python-list
mailing list