How to Print Specific Words in Color to Output Terminal in Python

share link

by vigneshchennai74 dot icon Updated: Feb 1, 2023

technology logo
technology logo

Guide Kit Guide Kit  

We can use ANSI escape codes to print specific words in color to the output terminal in Linux or macOS. ANSI escape codes are special sequences of characters that can be used to change the formatting of text in the terminal, including the color. Some commonly used ANSI escape codes for changing the color of text: 

  • \033[0;30m to \033[0;37m changes the text color to a color from black to white. 
  • \033[1;30m to \033[1;37m changes the text color to a color from black to white with bright effect. 
  • \033[4;30m to \033[4;37m changes the text color to a color from black to white with underline effect. 

ANSI escape codes are special sequences of characters that can be used to change the formatting of text in the terminal, including the color, font style, cursor position, and more. They are known as ANSI escape codes because they were originally defined by the American National Standards Institute (ANSI). You can also change font style to bold and underlining using ANSI codes. 

  • \033[1m sets text in bold 
  • \033[4m sets text in underline 

After applying the formatting, you can reset it back to default by sending \033[0m. 


To learn more about printing specific words in color to the output terminal, you may have a look at the code below. 

Preview of the output that you will get on running this code in your IDE

Code


  1. Copy this code using "Copy "button above and paste it in your python file IDE
  2. Run the code to get the texts coloured.


I have searched using "Print specific words in color to output terminal" in Kandi. you can try any use case

Environment Tested

I have tested this solution with following versions. Be mindful of changes when working with other versions


  • This solution is created and executed in Python 3.7.15 version


Using this solution we able to color the text using if case, printing the output depending on Output of the code . This process also facilities an easy to use, hassle free method to create a hands-on working version of code which would help us color the text in Python.

Support

  1. For any support on kandi solution kits, please use the chat
  2. For further learning resources, visit the Open Weaver Community learning page.

See similar Kits and Libraries