Python : coloration de texte

De Justine's wiki
Aller à la navigation Aller à la recherche

Colorer du texte dans un print

Pour colorer du texte, le plus simple est de la méthode suivante :

Print a string that starts a color/style, then the string, then end the color/style change with '\x1b[0m':

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

Success with green background example

Get a table of format options for shell text with following code:

<source lang="python"> def print_format_table():

   """
   prints table of formatted text format options
   """
   for style in range(8):
       for fg in range(30,38):
           s1 = 
           for bg in range(40,48):
               format = ';'.join([str(style), str(fg), str(bg)])
               s1 += '\x1b[%sm %s \x1b[0m' % (format, format)
           print(s1)
       print('\n')

print_format_table() </source>