How To Print Colored Text In Python - Studytonight

Studytonight is now part of the GUVI universe. Explore GUVI → 🤩 New Cool Developer Tools for you. Explore → FREE JavaScript Video Series Start Learning → Signup/Sign In
    Dark Mode On/Off
Interactive LearningInteractive Learning C Language course GO Lang course Learn JavaScript Learn HTML Learn CSS C LangC Language C Tutorial C Programs (100+) C Compiler Execute C programs online. CppC++ Language C++ Tutorial Standard Template Library C++ Programs (100+) C++ Compiler Execute C++ programs online. PythonPython Python Tutorial Python Projects Python Programs Python How Tos Numpy Module Matplotlib Module Tkinter Module Network Programming with Python Learn Web Scraping More in Python... Python Compiler Execute Python code online. JavaJava Core Java Tutorial Java Programs (100+) Java Code Examples (100+) Servlet JSP - Java Server Pages Java Type Conversion Examples Java Wrapper Class Spring Framework Java 11 More in Java... Java Compiler Execute Java code online. CAOComputer Sci. (GATE) Operating System Computer Architecture Computer Network DBDatabase DBMS Learn SQL MongoDB PL/SQL Practice SQL Execute SQL Queries online. More Tutorials... AndroidAndroid KotlinKotlin Game DevGame Development GO LanguageGO Language GIT GuideGIT Guide Linux GuideLinux Guide DockerDocker Spring FrameworkSpring Boot PHPPHP HTML TagsHTML Tags (A to Z) CSSCSS JavascriptJavaScript SASSSASS/SCSS Tests MCQs to test your knowledge. Compilers Compilers to execute code in browser.
  • Learn to Code
    • Interactive Courses, where you Learn by writing Code.
    • C LanguageC Language NEW
    • GO LangGO Language NEW
    • JavascriptJavaScript
    • CSSCSS
    • HTMLHTML
    • Projects/Concept Bundles
  • Library C Lang C Language

    C TUTORIAL

    Overview of C Language

    Compile & Run C Code

    What are Variables?

    C Operators (with Examples)

    See all →

    C PROGRAMS

    Armstrong Number Program

    Check Number is Odd/Even

    First n Prime Numbers

    Reverse String using Pointer

    See all Programs (100+) →

    INTERVIEW TESTS

    MCQs to test your C language knowledge.

    C Tests →

    EXECUTE CODE

    Run C programs and code examples online.

    C Compiler → Cpp C++ Language

    C++ TUTORIAL

    C++ Datatypes and Modifiers

    sizeof and typedef

    Create Class and Object

    See all →

    C++ PROGRAMS

    Check if Number is Positive/Negative

    Half Pyramid with Numbers

    Floyd's Triangle

    See all Programs (100+) →

    Data Structures → Standard Template Library → Advanced Data Structures →

    INTERVIEW TESTS

    MCQs to test your C++ language knowledge.

    C++ Tests →

    EXECUTE CODE

    Run C++ programs and code examples online.

    C++ Compiler → Python Python

    PYTHON TUTORIAL

    Python Installation & Setup

    Concept of OOP & Class

    Access Modifiers

    Python Projects →

    PYTHON HOW TOS

    Print Colored Text in Python

    Remove Numbers from String

    Compare two Dates

    See all How Tos (80+) →

    Tkinter → Matplotlib → NumPy → Python Programs → Network Programming → Web Scraping →

    INTERVIEW TESTS

    MCQs to test your Python knowledge.

    Python Tests →

    EXECUTE CODE

    Run Python code examples in browser.

    Python Compiler → Java Core Java JAVA TESTS MCQs to test your Java knowledge. EXECUTE JAVA CODE Run Java code in browser.

    JAVA TUTORIAL

    Setting Java Environment

    Concept of Constructor

    See all →

    JAVA CODE EXAMPLES

    Running a JAR File

    Serialization and Deserialization

    See all Examples (80+) →

    Spring Framework SPRING TUTORIAL

    Spring Framework

    Spring Boot

    Spring Security

    MORE IN JAVA

    Java Library Functions

    Type Conversion Examples

    Java 11 Features

    See all →

    Computer Science Computer Science

    CAO COMPUTER ARCHITECTURE

    Basics Of Digital Components

    Different type of Logic gates

    Memory organization

    See all →

    Computer Network COMPUTER NETWORK

    Types of Computer Networks

    Transmission Mediums

    ISO/OSI model

    See all →

    Operating System OPERATING SYSTEM

    Types of Operating System

    Process Scheduling

    CPU Scheduling

    First come First Serve

    Shortest Job First

    Classical Synchronization Problem

    What are Semaphores?

    What are Deadlocks?

    See all →

    DBMS Database

    DBMS & SQL

    ER Model

    Relational Algebra & Calculus

    Types of DBMS Keys

    Database Normalization

    See all →

    PL/SQL

    Datatypes in PL/SQL

    PL/SQL Procedures

    How to create Cursor?

    See all →

    MongoDB

    MongoDB vs. RDBMS

    Installing MongoDB

    Using MongoDB with Java

    See all →

    EXECUTE SQL

    Practice SQL Query in browser with sample Dataset.

    Run SQL Query → (Learn SQL Queries) More...

    AndroidANDROID DEVELOPMENT

    GOGO LANGUAGE

    linuxLINUX

    dockerDOCKER

    HTMLHTML TAGS (A to Z)

    cssCSS REFERENCES

    sassSASS/SCSS

    kotlinKOTLIN

    unity 3dGAME DEVELOPMENT

    phpPHP

    gitGIT GUIDE

    javascriptJAVASCRIPT

    dsaADVANCED DSA

  • Tests
  • CoursesNEW
coins 500 coins Login Pandas SASS/SCSS JavaScript Spring Boot HTML 5 References Docker Python Built-in Functions Kotlin C++ Programs Java Examples Java 8 Tkinter Elasticsearch GIT Guide Linux Guide Matplotlib Java 9 Java Wrapper Classes Index Explore: Tutorials Library MCQ Tests Curious? Learn Coding!
  • Python Basics
    • Float Round to Two Decimals
    • Check if a Variable Exists
    • Check Python Version
    • Yield keyword in
    • Upgrade Python Packages
    • Generate Random Value
    • Assert in Python
    • Underscore in Python
    • Convert Byte To Hex
    • Comment in Python
    • Error Handling in Python
    • Normal vs Keyword Arguments
    • Scope of variable in If Statement
  • Python OOPS
    • Create Class
    • Create an Object
    • Static vs Class Method
    • Find All SubClasses
    • Pass Method as Argument
  • Python String
    • Print Colourful Text
    • String Slicing
    • Remove numbers from String
    • String to Char Array
    • Remove trailing newlines
    • Create MultiLine String
    • Convert String to String Array
    • Convert String to Byte
    • Convert Byte to String
    • Remove Space from String
    • Count the String Occurrence
    • Convert String to UTF-8
    • Replace String
    • MD5 Sum Of String
    • Decode HTML Entities
  • Python List
    • Convert List to String
    • Concatenate Lists
    • Find Average of a List
    • Find Max From List
    • List Subtraction
    • Count Unique Values in List
    • Creating Array
    • Check List Same Elements
    • Lists to Dictionary
    • Del, Remove and Pop
    • Permutation of List
    • Merge Two Lists
    • Longest String in List
    • Print Random from List
    • How to Slice
    • How to add
    • List as Argument
    • Delete From List
    • Tuple to List
    • Read List Elements
    • Rotate a List
    • Two List Addition
  • Python Tuple
    • Pass Tuple as an Argument
    • How to Add
  • Python Date & Time
    • Compare Two Dates
    • Add Days to Date
    • Current date and time
    • Get Year from Date
    • Python Execution Time
    • Convert Seconds to Minutes
    • Date to String
    • Convert DateTime to Seconds
    • Get Month Name
  • Python Set
    • Join two Sets
    • Add Elements into Set
    • Delete Elements from Set
    • Access Set Elements
    • Set with range
    • Create an Immutable Set
    • Add List to Set
  • Python Dictionary
    • Find Key From Value in Dictionary
    • Reverse Dictionary
    • Check Value Exists in Dictionary
    • List of Value From Dictionary
  • Python File and I/O
    • Unzip File
    • Read XML file in python
    • Read CSV file in Python
    • Read JSON File
    • Check File Size
    • List all files
    • Read YAML in Python
    • Read CSV To List
    • Append Text To a File
    • Check File Exist in Python
    • Find files with Certain Extension
    • Get Last of Path
    • Read File From Line 2
    • Search and Replace File Text
    • Read First Line
    • Get The Home Directory
    • Search and Replace Text in File
    • Check If File is Empty
  • Python JSON
    • Print Pretty JSON
    • Convert JSON to Dictionary
  1. Home
  2. Python How Tos
  3. How to Print Colored Text in Python
LAST UPDATED: JULY 21, 2023How to Print Colored Text in Python

In this article, you will learn how to print colored text in Python. We will use some built-in modules and libraries and some custom Python code as well to print color text in Python. Let's first have a quick look at how Python represents color codes.

In the Python programming language, text can be represented using different colors. There are very simple-to-use Python libraries for colors and formatting in the terminal. Your program or script's output will look better if you print colored texts.

Let's see some code examples to print color text in Python.

1. Print color text using Colorama Package

  • You can use the Colorama package of Python to print colorful text on the terminal.

  • To install the Colorama package, you can use pip install colorama command.

  • The Colorama module provides a constant shorthand for ANSI escape sequences that can be used for colored text in Python.

  • Just import the Fore class from the Coloroma package and start using colors in your print() function.

from colorama import Fore print(Fore.RED + 'This text is red in color')

This text is red in color

There are other classes too in the Colorama package that you can use to style text in Python.

  1. Back - Add background color to the text

  2. Style - Add some style like dim the text.

Let's see a code example,

from colorama import  Back, Style print(Back.GREEN + 'The text with Green background') print(Style.DIM + 'The text is DIM now')

Here is a list of values that you can try:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET. Style: DIM, NORMAL, BRIGHT, RESET_ALL

Enjoy colored text in the Python terminal.

2. Print color text using termcolor Package

  • You can use the termcolor package also to print text color in Python.

  • The termcolor is a Python package for ANSII Color formatting for the text output in the terminal.

  • For using the termcolor package, you need the sys package imported first in your Python script and then use the colored method from termcolor module as given below:

import sys from termcolor import colored, cprint text = colored('Hello, World!', 'red', attrs=['reverse', 'blink']) print(text)

Hello, World!

You can also add more effects to the text on the terminal using the termcolor package.

3. Print color text using ANSI code in Python

  • You can use ANSI code style to make your text more readable and creative.

  • You can use ANSI escape codes to change the color of the text output in the Python programs.

  • A good use case for this is to highlight errors. The escape codes are entered right into the print statement.

print("\033[1;32m This text is Bright Green  \n")

This text is Bright Green

The above ANSI escape code will set the text color to bright green. The format is;

  • \033[ = Escape code, this is always the same

  • 1 = Style, 1 for normal.

  • 32 = Text color, 32 for bright green.

Here is a list of other colors:

print("\033[1;37;40m \033[2;37:40m TextColour BlackBackground TextColour GreyBackground WhiteText ColouredBackground\033[0;37;40m\n") print("\033[1;30;40m Dark Gray \033[0m 1;30;40m \033[0;30;47m Black \033[0m 0;30;47m \033[0;37;41m Black \033[0m 0;37;41m") print("\033[1;31;40m Bright Red \033[0m 1;31;40m \033[0;31;47m Red \033[0m 0;31;47m \033[0;37;42m Black \033[0m 0;37;42m") print("\033[1;32;40m Bright Green \033[0m 1;32;40m \033[0;32;47m Green \033[0m 0;32;47m \033[0;37;43m Black \033[0m 0;37;43m") print("\033[1;33;40m Yellow \033[0m 1;33;40m \033[0;33;47m Brown \033[0m 0;33;47m \033[0;37;44m Black \033[0m 0;37;44m") print("\033[1;34;40m Bright Blue \033[0m 1;34;40m \033[0;34;47m Blue \033[0m 0;34;47m \033[0;37;45m Black \033[0m 0;37;45m") print("\033[1;35;40m Bright Magenta \033[0m 1;35;40m \033[0;35;47m Magenta \033[0m 0;35;47m \033[0;37;46m Black \033[0m 0;37;46m") print("\033[1;36;40m Bright Cyan \033[0m 1;36;40m \033[0;36;47m Cyan \033[0m 0;36;47m \033[0;37;47m Black \033[0m 0;37;47m") print("\033[1;37;40m White \033[0m 1;37;40m \033[0;37;40m Light Grey \033[0m 0;37;40m \033[0;37;48m Black \033[0m 0;37;48m")

color text in Python output

4. Print color text using the colored package

  • You can use the colored package and its functions to color text in Python.

  • It is a library that can be used after installation by using the pip command.

  • So, first, install it and then import it into your Python script to highlight text colors.

from colored import fg print ('%s Hello World !!! %s' % (fg(1), attr(0)))

Hello World !!!

4. 1 Code Example using colored package

We can pass the name of the color into the fg() function.

The code example below prints text in blue color as we passed blue as the value.

from colored import fg color = fg('blue') print (color + 'Hello World !!!')

Hello World !!!

Conclusion

These are the different ways in which you can print your text in different colors in Python. You can also add different styles to your text, different background colors to your text as well.

You learned how to color text in Python and print colored backgrounds on the terminal using several packages such as coloroma package, termcolor package, colored package etc.

  • ← Pass Method as Argument← PREV
  • String Slicing →NEXT →
Want to learn coding? Try our new interactive courses. View All → C language C Language CourseNEW 115+ Coding Exercise GO lang course GO Language Course 4.5 (50+) | 500+ users Javascript course JS Language Course 4.5 (343+) | 6k users CSS course CSS Language Course 4.5 (306+) | 3.3k users HTML course HTML Course 4.7 (2k+ ratings) | 13.5k learners Over 20,000+ students enrolled. About the author: yuktijain An enthusiastic fresher, a patient person who loves to work in diverse fields. I am a creative person and always present the work with utmost perfection. Learn to Code Learn and practice coding side-by-side. NEW C language Course 115+ coding exercises Javascript Course 85+ coding exercises More →

Tag » Color Print Python 3