Python 3 how to print colors and tab aligned

Python offers several ways of formatting and doing tricks like adding colors to the output and aligning the text in columns - left or right. Below you can see simple example before and after formating and the big difference in the output:

Selection_036

There many ways to add color in python:

  • Colorama - my preferred way of adding colors. It can be installed by:
pip install colorama
  • Using print format like:
print('\x1b[1;15;37m' + 'I'm in color' + '\x1b[0m')

The format is the following:

color_start = '\033[45m'
color_end = '\033[0m'
print(color_start + "I'm in color" + color_end)

If you skip the color end all the rest of your prints will be in the same color.

The same for text align you have several option:

  • Using string functions like ljust
print 'Bitcoin'.ljust(15)
  • using formatting:
print('{:<15s}{:>6s}{:>20s}{:>15s}'.format(coins[i][0],coins[i][1],coins[i][2],coins[i][3]))

In the example below I'm using colorama and formatting:

from colorama import Style, Fore

coins = [['NAME', '#', 'Price', 'Change (%)'],
        ['Bitcoin', 1, '$7,430.07', 1.22],
        ['Ethereum', 2, '$461.02', -3.43],
        ['XRP', 3, '$0.46150', -3.90],
        ['Bitcoin Cash', 4, '$804.32', -1.70],
        ['EOS', 5, '$8.11', -4.29],
        ['Stellar', 6, '$0.29635', 0.91]]

dash = '-' * 60

def color(val):

    if val > 0:
        out = Fore.RED + str(val) + Style.RESET_ALL
    else:
        out = Fore.GREEN + str(val) + Style.RESET_ALL
    return out


for i in range(len(coins)):
    if i == 0:
      print(dash)
      print('{:<15s}{:>6s}{:>20s}{:>15s}'.format(coins[i][0],coins[i][1],coins[i][2],coins[i][3]))
      print(dash)
    else:
      print('{:<15s}{:>6d}{:>20s}{:>7s}{:>15s}'.format(coins[i][0],coins[i][1],coins[i][2],"",color(coins[i][3])))


print(dash)
print('{}, {}, {}, {}'.format(coins[0][0],coins[0][1],coins[0][2],coins[0][3]))
print(dash)
for i in range(1, len(coins)):
      print('{}, {}, {}, {}'.format(coins[i][0],coins[i][1],coins[i][2],coins[i][3]))

result(this is shown without the colors:

------------------------------------------------------------
NAME                #               Price     Change (%)
------------------------------------------------------------
Bitcoin             1           $7,430.07         1.22
Ethereum            2             $461.02        -3.43
XRP                 3            $0.46150         -3.9
Bitcoin Cash        4             $804.32         -1.7
EOS                 5               $8.11        -4.29
Stellar             6            $0.29635         0.91
------------------------------------------------------------
NAME, #, Price, Change (%)
------------------------------------------------------------
Bitcoin, 1, $7,430.07, 1.22
Ethereum, 2, $461.02, -3.43
XRP, 3, $0.46150, -3.9
Bitcoin Cash, 4, $804.32, -1.7
EOS, 5, $8.11, -4.29
Stellar, 6, $0.29635, 0.91

The final outlook is like in this picture:

Selection_036

Related Article