Emelda Showmen
Emelda Showmen

Reputation: 47

Why does "\t" in python make output automatically align to the left?

In my homework I was told to make a power table with 5 rows and 10 columns. Value of the power table at row i, column j is j^i and the column should be spaced with a tab.

row = 5
column = 10

i = 1
while i <= row:
    j = 1
    while j <= column:
        print(j ** i, end='\t')
        j += 1
    print("")
    i += 1

And here is the output:

This works very well, but I don't understand why every column is automatically aligned to the left. Shouldn't '\t' create a tab that has the same length of 4 spaces every time? For example, the spaces in the last 2 columns between "9 and 10" and "59049 and 100000" are apparently not equal. Why is that?

Upvotes: 1

Views: 2148

Answers (1)

Emily
Emily

Reputation: 541

That's how it's supposed to work.

A tab character, when printed to a terminal, becomes enough spaces to space up to the next multiple of 8*. (This makes it useful for making tables.)

So if you print pairs of numbers separated by tabs, you get:

        | <-- 8 characters is here
1       23456
12      3456
123     456
1234    56

etc. But you can't see this effect when you're using them to indent, because when there's nothing in front of them they all come out full width, so you get:

        | <-- 8 characters is here
non-indented stuff
        indented stuff

* Tab size is configurable in many text editors, but generally not in terminals, where you get the traditional default of 8.

Upvotes: 4

Related Questions