Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python spacing issue when printing color to console

Tags:

python

console

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
like image 319
John Holmes Avatar asked May 02 '26 21:05

John Holmes


1 Answers

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")
like image 130
Joe Avatar answered May 04 '26 11:05

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!