Printing with "\T" (Tabs) Does Not Result in Aligned Columns

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

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.

Why the first \t doesn't work?

It works fine for me. (example)

Output:

toes=10 2toes=20        toes2=100

Note that \t means "tabulate", or in other words to pad to the nearest multiple of N position, where N is usually 8.

toes=10 takes up 7 characters, so to reach the next multiple of 8 would require printing 1 space.

Python Output not Aligned Using Space and Tab

For statement

    print(day+1, "\t    ", daily, "\t\t    ", totalSalary)

each '\t' will stop at 1, 9, 17, ..., at each 8th character

So it will look like this

1=------____=1=-........____=1
2=------____=2=-........____=3
3=------____=4=-........____=7
4=------____=8=-........____=15
5=------____=16=--------........=31
6=------____=32=--------........=63
12345678123456781234567812345678 <--- Tab stop before each 1

Here

  • = is the separator space between each two arguments of print
  • - is the space generated by not-last TAB
  • _ is the space specified by you in your print.
  • . is the sapce generated by last TAB.

From here you can find the differece why they stop at different position.

Try to add option sep='' in your print, or change the numbers of spaces you added.

    print(day+1, "\t    ", daily, "\t\t    ", totalSalary, sep='')

then it will be fine.

How many days did you work? : 6
Day Daily Salary Total Salary
1 1 1
2 2 3
3 4 7
4 8 15
5 16 31
6 32 63

Incorrect column alignment when printing table in Python using tab characters

One possible solution is to rely on some package that has been designed for this purpose, like tabulate: Read more about it!

Keep in mind that you have to install this using e.g. pip install tabulate

from tabulate import tabulate

print tabulate([[00, 00, 00], [00, 00, 00], [00, 00, 00]], headers=['X Coordinate','Y Coordinate','Result'], tablefmt='orgtbl')

Or use your original table with this code:

alignment = len(max(table.split("\t")))+1

for line in table.strip().split("\n"):
row ="{{:>{}}}".format(alignment) * len(line.strip().split("\t"))
print row.format(*line.strip().split("\t"))

Aligning file output with \t

You need to know how many spaces are equivalent to a tab. Then you can work out how many tabs are covered by each entry.

If tabs take 4 spaces then the following code works:

$TAB_SPACE = 4;
$NUM_TABS = 4;
foreach my $key (sort {$month{$a} <=> $month{$b}} keys %month) {
my @fullName = split(/ /, $namelist{$key});
my $name = "$fullName[1], $fullName[0]";

# This rounds down, but that just means you need a partial tab
my $covered_tabs = int(length($name) / $TAB_SPACE);

print $name . ("\t" x ($NUM_TABS - $covered_tabs)) . $doblist{$key}\n";
}

You need to know how many tabs to pad out to, but you could work that out in a very similar way to actually printing the lines.

printf alignment with tabs in C

TAB is still 1 character. It is printed as 1 character. Then it's up to the terminal to do whatever it wants with it.

This means, printf("%-20s", "\tstring3"); is going to print 1 TAB character, 7 normal characters, and then 12 spaces to arrive at 20.

You need to re-think what you want to do. One way would be to create a function which takes in the string with TABs in it, and returns a string where those have been expanded to spaces. If TAB is always at the start of the string, then you could just replace TABs with 8 (or however many you need) spaces. If you need actual TAB stops, you need a bit more logic to expand them to right amount of spaces.

Create nice column output in python

data = [['a', 'b', 'c'], ['Printing with "\T" (Tabs) Does Not Result in Aligned Columnsaa', 'b', 'c'], ['a', 'bb', 'c']]

col_width = max(len(word) for row in data for word in row) + 2 # padding
for row in data:
print "".join(word.ljust(col_width) for word in row)

a b c
Printing with "\T" (Tabs) Does Not Result in Aligned Columnsaa b c
a bb c

What this does is calculate the longest data entry to determine the column width, then use .ljust() to add the necessary padding when printing out each column.

How can I clean up misaligned columns in text?

Presumably you are using printf to output the columns in the first place. You can use extra modifiers in your format string to make sure things get aligned.

  • To print a column of a specific width (right-justified), add the width before the formatting flag, e.g., "%10s" will print a column of width 10. If your string is longer than 10 characters, the column will be longer than you want, so choose a maximum value. If the string is shorter, it will be padded with spaces.
  • To left-justify a column, put a - sign in front, e.g., "%-10s". I like to left-justify strings and right-justify numbers, personally.
  • If you are printing addresses, you can change the fill characters from spaces to zeroes with a leading zero: "%010x".

To give a more in depth example:

printf("%-30s %8s %8s\n", "Name", "Address", "Size");
for (i = 0; i < length; ++i) {
printf("%-30s %08x %8d\n", names[i], addresses[i], sizes[i]);

This would print three columns like this:

Name                            Address     Size
foo 01234567 346
bar 9abcdef0 1024
something-with-a-longer-name 0000abcd 2048


Related Topics



Leave a reply



Submit