How print colorful text in Python | Python Tutorial

In Python Tutorial in Hindi, We will Learn how print colorful text in Python using TermColor Library.

In this video tutorial going to cover:

  1. How do you type in color text?
  2. What Colour is a string in Python?
  3. How do you change text color in idle Python?
  4. What are the colors in python?
  5. How do you make text bold in Python?

Termcolor : ANSII Color formatting for output in terminal.

Termcolor Installation

$ pip install termcolor

Text Properties

Text colors:

  • grey
  • red
  • green
  • yellow
  • blue
  • magenta
  • cyan
  • white

Text highlights:

  • on_grey
  • on_red
  • on_green
  • on_yellow
  • on_blue
  • on_magenta
  • on_cyan
  • on_white

Attributes:

  • bold
  • dark
  • underline
  • blink
  • reverse
  • concealed

Terminal properties

Terminalbolddarkunderlineblinkreverseconcealed
xtermyesnoyesboldyesyes
linuxyesyesboldyesyesno
rxvtyesnoyesbold/blackyesno
dttermyesyesyesreverseyesyes
teratermreversenoyesrev/redyesno
aixtermnormalnoyesnoyesyes
PuTTYcolornoyesnoyesno
Windowsnonononoyesno
Cygwin SSHyesnocolorcolorcoloryes
Mac Terminalyesnoyesyesyesyes

Examples:

## Termcolor Library: ANSII Color formatting for output in terminal.

# Import Libraries
from termcolor import colored

print("warning")
print("Done")

### Text colors:

warning = colored("warning", "red")
done = colored("done", "green")

print(f"[{warning}] Virus in running")
print(f"[{done}] Virus killed")

### Text highlights:
warning = colored("[warning]", "red", "on_grey")
done = colored("[done]", "green", "on_grey")

print(f"{warning} Virus in running")
print()
print(f"{done} Virus killed")

### Attributes
warning = colored("[warning]", "red", "on_grey", attrs=['reverse'])
done = colored("[done]", "green")

print(f"{warning} Virus in running", end = "\n")

print(f"{done} Virus killed", end="\n")

done = colored("[done]", "green", attrs=['bold'])
print(f"{done} Virus killed")

done = colored("[done]", "green", attrs=['underline'])
print(f"{done} Virus killed")

done = colored("[done]", "green", attrs=['reverse'])
print(f"{done} Virus killed")


######### Downloading Bar
import time

for j in range(1,101):
    time.sleep(.02)
    
    downloading = colored("Collecting Data", 'yellow', 'on_grey', attrs=['reverse'])
    percentage = colored(f"[{j}%]", 'blue')
    bar = colored('|' * j, "green")
    color = downloading + percentage + bar
    
    print(color, end="\r")
    
print("\n", end="\n")

for j in range(1,101):
    time.sleep(.2)
    
    downloading = colored("Downloading", 'red', 'on_grey', attrs=['reverse'])
    percentage = colored(f"[{j}%]", 'blue')
    bar = colored('|' * j, "green")
    color = downloading + percentage + bar
    
    print(color, end="\r")

REF: https://pypi.org/project/termcolor/

Leave a Reply

Top