Pigna
Pigna

Reputation: 2924

Why newlines are not color-formatted?

I have followed this solution in order to color-format a matrix on the terminal. However when I print it, the newlines I have added in order to separate the lines of the matrix are not formatted. I expected the whole terminal to become background white and black text (for the area corresponding to the matrix height), but clearly it is not. Why?

This is the code:

m = np.full((4,4),'0',dtype=np.str_)
print('\x1b[0;30;47m\n'+'\n\n'.join('   '+'   '.join(line) for line in m)+'\n\x1b[0m')

PROOF: enter image description here I am using the default ubuntu 14.04 terminal

SOLVED In the end I simply applied the color-formatting to each string of characters separated by a new line.

Upvotes: 0

Views: 588

Answers (2)

Thomas Dickey
Thomas Dickey

Reputation: 54562

Cell backgrounds are colored only where the screen is updated. When your program prints a newline, it "only" makes the cursor position move down (no cells are updated).

However, if you modify your program to print more lines, i.e., going down to the bottom of the screen, it will do something different:

  • the cursor can no longer move down.
  • the screen "indexes" (scrolls up by one line), and
  • the newly exposed line will be colored.

That is because the terminal copies the behavior from xterm and Linux console. There are actually several features of the terminal which combine to form its behavior when erasing portions of the screen.

Further reading:

Upvotes: 1

Błotosmętek
Błotosmętek

Reputation: 12927

I think the reason for this behaviour is that most terminals only apply background colour to the characters that are actually printed, but \n\n produces a line containing no characters (rather than a line full of spaces). At least that's what all the terminals I had at hand did. Try this:

print('\x1b[0;30;47m\n' + '\n'.join([' '*i for i in range(10)]) + '\n\x1b[0m')

and you'll likely see a stair-like pattern: stair-like pattern

Upvotes: 1

Related Questions