Python使用空格与Tab实现输出对齐时最后两行错位的原因咨询
First, let's recap your code and the output you're seeing to make sure we're on the same page.
Your Code
days = int(input("How many days did you work? : ")) totalSalary = 0 print("Day", " Daily Salary", " Total Salary") for day in range(days): daily = 2**day totalSalary += daily print(day+1, " ", daily, " ", totalSalary)
Output When Inputting 6
Day Daily Salary Total Salary
1 1 1
2 2 3
3 4 7
4 8 15
5 16 31
6 32 63
The Root Cause: How Tabs Work (Not Fixed Spaces!)
The misalignment happens because tabs don't behave like a fixed number of spaces—they're designed to jump to the next predefined tab stop (usually every 4 or 8 characters in most terminals). When you mix tabs, manual spaces, and the automatic spaces Python adds between print() arguments, you create a perfect storm of inconsistent spacing.
Here's the breakdown:
- Let's say your terminal uses 4-character tab stops. When you print
5(1 character), the tab after it jumps to the next multiple of 4 (position 4), then you add a space—so16starts at position 5. - When you print
6(also 1 character), the tab jumps to the same position 4, space to 5, and32starts there too. The misalignment becomes visible because whendailygoes from 8 (1 digit) to 16 (2 digits), the total length of thedailycolumn increases by 1 character. This shifts the starting position of the tabs you added afterdaily, which then jump to a different tab stop than they did for shorter numbers. - Python also adds an extra space between each argument in your
print()call, so you're getting a mix of: Python's auto-spaces + your manual tabs + your manual spaces. This compounded inconsistency makes the alignment break as numbers grow in length.
As Jason Yang's visual explanation of tab stops clarified, think of your terminal as being split into equal-width "cells" (e.g., 4 characters wide). A tab doesn't fill space—it skips directly to the start of the next cell. If the content before the tab takes up part of a cell, the tab will jump the remaining distance to the next cell's start. Different-length content will leave different amounts of space in the cell, so the tab's jump destination changes, throwing off the alignment of everything after it.
内容的提问来源于stack exchange,提问作者Albatros

