Python's built-in print function can output text with custom colors and styles using ANSI escape codes. The general format is \[display_style];[foreground_color];[background_color]m followed by the text, and then \[0m to reset the formatting.
Display Styles:
0: Default1: Bold4: Underline5: Blink7: Reverse video
Example for display styles:
print("\033[0mDefault text\033[0m")
print("\033[1mBold text\033[0m")
print("\033[4mUnderlined text\033[0m")
print("\033[5mBlinking text\033[0m")
print("\033[7mReversed text\033[0m")
Color Codes:
- Foreground:
30(Black),31(Red),32(Green),33(Yellow),34(Blue),35(Magenta),36(Cyan),37(White) - Background:
40(Black),41(Red),42(Green),43(Yellow),44(Blue),45(Magenta),46(Cyan),47(White)
These can be combined with display styles.
Example for colors and styles:
print("\033[31mRed text\033[0m")
print("\033[1;32mBold green text\033[0m")
print("\033[4;33mUnderlined yellow text\033[0m")
print("\033[37;44mWhite text on blue background\033[0m")
print("\033[1;30;47mBold black text on white background\033[0m")
For a cross-platform solution, the colorama libray is recommended.
Installation:
pip install colorama
colorama provides constants for easy formatting:
Fore:BLACK,RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE,RESETBack:BLACK,RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE,RESETStyle:DIM,NORMAL,BRIGHT,RESET_ALL
Basic Usage:
from colorama import Fore, Back, Style
print(Fore.RED + "This text is red.")
print(Back.GREEN + "This text has a green background.")
print(Style.DIM + "This text is dim.")
print(Style.RESET_ALL + "This text is back to normal.")
The init() function can be used to manage color output, especial for cross-platform compatibility. Setting autoreset=True automatically adds Style.RESET_ALL after each print statement, simplifying code.
Autoreset Example:
from colorama import init, Fore
init(autoreset=True)
print(Fore.BLUE + "This text is blue and will reset automatically.")
print("This text is now back to the default color.")