python spacing issue when printing color to console

Viewed 242

Im trying to print colored headers to the console but it seems to be messing with the spacing. Why does it ignore the spacing?

yellow = lambda text: '\033[0;33m' + text + '\033[0m'
print(f"{yellow('Header1'):<15} {'Header2':<15} Header2")

Output:

Header1 Header2         Header2
2 Answers

Because it uses the text returned from the lambda function to count the string length:

In:

len(yellow('Header1'))

Out:

18

Apparently the length to add the spaces is evaluated before the interpretation of the character as color information. Which I think makes sense because the color is probably only interpreted later by the sys.stdout.

If you do the following, for instance, you get some spaces back:

In:

yellow = lambda text: '\033[0;33m' + text + '\033[0m'^M
print(f"{yellow('Header1'):<20} {'Header2':<15} Header2")

Out:

Header1   Header2         Header2

The issue is the padding you added for the yellow color. Here's what the format string is converted to on line 2:

Initial version

print(f"{yellow('Header1'):<15} {'Header2':<15} Header2")

After yellow('Header1') is evaluated

print(f"{'\033[0;33mHeader1\033[0m':<15} {'Header2':<15} Header2")

You can see that the length is over 15 characters long. Once the statement is printed, your console will convert the special characters and change Header1 to yellow text. To fix the issue, you can add the yellow padding outside of the {'Header1':<15} format.

Something like this could work:

print(yellow(f'{'Header1':<15}') + f' {'Header2':<15} Header2")
Related